~/ 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/a888c5ce-47be-4543-aaf8-afdb981f23de/flashcard utf-8 LF