Unit 3 Cycle 2 Day 25: Polymorphism: Multiple Method Calls
Share
Polymorphism: Multiple Method Calls
Section Mixed — Review: Polymorphism
Key Concept
Complex polymorphism problems involve multiple method calls on the same object, some overridden and some inherited. Each call must be resolved independently: check the runtime type for overrides, fall back to the superclass for non-overridden methods. The AP exam chains these calls in sequence, where earlier calls may modify state that affects later calls. The challenge is maintaining accurate object state while correctly resolving each method call to the right class version.
Consider the following classes.
What does new Sub().info() return?
Answer: (B) "Sub! Sub"
Sub.info() calls super.info() which is Base.info(). Base.info() calls name(). Since the object is a Sub, name() returns "Sub". So super.info() returns "Sub!". Then Sub.info() appends " " + name() = " Sub". Result: "Sub! Sub".
Why Not the Others?
(A) Even inside super.info(), name() dispatches to Sub's version because the object is a Sub.
(C) The object is a Sub, so all name() calls resolve to Sub's override.
(D) name() always returns "Sub" for a Sub object, regardless of where it is called from.
Common Mistake
This is a tricky polymorphism case. Even when super.info() executes Base's code, any call to an overridden method (like name()) still uses the Sub's version because dynamic dispatch applies.
AP Exam Tip
Dynamic dispatch is not affected by super calls. super.info() runs Base's info code, but within that code, name() still dispatches to the actual object's version (Sub).