~/ learn/ java-from-zero/ cards/ Casting, instanceof & pattern matching
1 of 4

Type a downcast guarded by instanceof

Type a downcast guarded by instanceof

Answer

if (a instanceof Dog) { Dog d = (Dog) a; d.fetch(); }

instanceof tests whether the object's runtime type is Dog (or a subclass). Without this guard, the cast might throw ClassCastException if a holds a non-Dog.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/9bf4ac62-e755-4d28-abb4-e97b84c794cb/flashcard utf-8 LF