Polymorphism lets a superclass reference point to subclass objects and invoke overridden methods at runtime—Animal a = new Dog(); a.speak(); prints "Woof".
Upcasting and dynamic dispatch
The JVM resolves the actual method implementation based on the object's runtime type, not the reference type (for instance methods).
instanceof and casting
if (pet instanceof Dog d) {
d.fetch();
}
Pattern matching for instanceof (Java 16+) avoids manual cast boilerplate.
Important interview questions and answers
- Q: Compile-time vs runtime type?
A: Reference type is compile-time; object on heap is runtime—dynamic dispatch uses runtime type. - Q: Can static methods be overridden?
A: No—they are hidden, not overridden; polymorphism applies to instance methods.
Self-check
- Why store a
Dogin anAnimalvariable? - When do you need an explicit cast?