~/ learn/ comp-308/ cards/ Designing with inheritance; downcasting & RTTI preview
1 of 5

Guard a downcast with instanceof

Guard a downcast with instanceof

Answer

if (v instanceof Car) { Car c = (Car) v; c.honk(); }

`instanceof` confirms the real type before the explicit downcast, so the `(Car) v` cast can never throw `ClassCastException` and `v` being null is ruled out.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/ee2130df-cb5d-4023-bbe2-bbe12f72648c/flashcard utf-8 LF