Unit 3 Cycle 2 Day 11: Complex Polymorphism Tracing
Share
Complex Polymorphism Tracing
Section 3.15 — Creating References
Key Concept
Complex polymorphism tracing involves multiple objects of different types stored in the same variable or collection, with each method call resolving to the appropriate override. The trace requires checking: (1) does the compile-time type allow this method call? (2) does the runtime type override this method? (3) if the overridden method calls super.method(), which version runs? Each of these checks must be performed at every method call. The AP exam's hardest polymorphism questions chain multiple calls with super references.
Consider the following classes.
What does new B().display() return?
Answer: (B) "B!"
B inherits display() from A. display() calls show(). Since the object is a B, Java uses B's overridden show() returning "B". display() returns "B!".
Why Not the Others?
(A) Even though display() is defined in A, it calls show() which is overridden in B. Dynamic dispatch uses B's version.
(C) Only one version of show() is called, not both.
(D) B inherits display() from A. No compile error.
Common Mistake
This is dynamic dispatch: when a parent method calls a method that the child overrides, the child's version is used. The actual object type (B) determines which show() runs.
AP Exam Tip
Dynamic dispatch is the most important polymorphism concept. A parent method calling a virtual (overridden) method uses the child's version at runtime.