instanceof and the Type Hierarchy
What you'll learn: How instanceof checks an object against its entire inheritance chain, not just its direct class.
The Big Picture
When you use instanceof, Java doesn't just check if an object is exactly that type—it checks whether the object is compatible with that type anywhere in its inheritance hierarchy. This means instanceof returns true for:
- The object's actual class
- Any superclass the object inherits from
- Any interface the object implements (directly or inherited)
- Any abstract class in the hierarchy
Think of it like asking "Can this person perform this role?" A SoftwareEngineer might be checked against Engineer, Employee, or even Person—all would return true because they're all part of the same family tree.
How It Works
class Animal { }
class Dog extends Animal { }
class Beagle extends Dog { }
Beagle myPet = new Beagle();
// All of these return true:
myPet instanceof Beagle // direct class
myPet instanceof Dog // parent class
myPet instanceof Animal // grandparent class
myPet instanceof Object // ultimate ancestor
Even if you upcast the reference, the actual object type is what matters:
Animal a = new Beagle(); // upcast reference
a instanceof Beagle // true - actual object is Beagle
a instanceof Dog // true - Beagle inherits from Dog
a instanceof Animal // true - Beagle inherits from Animal
The reference type (Animal) doesn't limit what instanceof sees—it always checks the real object living in memory.
Key Takeaway:
instanceof tests an object against its entire type hierarchy—returning true for the object's class, all its superclasses, and all interfaces it implements, making it a "family tree" check rather than an exact-type-only test.