~/ 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/e17f6566-5fd0-4dc0-a6b0-8b23459362fb/flashcard utf-8 LF