Unit 3 Cycle 1 Day 15: Polymorphism with Method Calls
Share
Polymorphism with Method Calls
Section 3.15 — Creating References
Key Concept
When a method is called on a polymorphic reference, Java uses dynamic dispatch to determine which version of the method to execute. If the subclass overrides the method, the subclass version runs, even though the reference type is the superclass. If the subclass does not override the method, the superclass version runs. This runtime determination is the core of polymorphism. On the AP exam, you must trace method calls by checking: does the actual object's class override this method? If yes, use the override; if no, use the inherited version.
Consider classes where Dog extends Animal. Dog has a method fetch() not in Animal.
Which line causes a compile-time error?
Answer: (C) a.fetch();
a is declared as type Animal. The compiler only sees Animal's methods. fetch() is not in Animal, so a.fetch() causes a compile error even though the actual object is a Dog.
Why Not the Others?
(A) A parent reference can hold a child object. This is valid polymorphism.
(B) sound() is defined in Animal, so the compiler allows it. At runtime, Dog's version runs.
(D) d is declared as Dog, so all Dog methods (including fetch) are visible.
Common Mistake
The compile-time type determines what you can call. Even though the object IS a Dog, if the reference is Animal, you cannot call Dog-specific methods without casting.
AP Exam Tip
Compile-time type = what methods are available. Runtime type = which version runs. This distinction is critical for AP exam polymorphism questions.