Unit 3 Cycle 2 Day 8: Polymorphism with toString
Share
Polymorphism with toString
Section 3.16 — Object Superclass
Key Concept
When toString() is called on a polymorphic reference, the runtime type's version executes. System.out.println(obj) automatically calls obj.toString(). If the subclass overrides toString(), that version prints even when the reference type is the superclass. If the subclass does not override it, Java looks up the hierarchy until it finds a version. The AP exam tests chains where println calls toString() implicitly, and the actual output depends on which class in the hierarchy provides the override.
Consider the following classes.
What does System.out.println(new Truck(5)); print?
Answer: (B) Truck (5T)
Truck's toString(): calls super.toString() which returns "Truck" (the type field), then appends " (5T)". Result: "Truck (5T)".
Why Not the Others?
(A) Truck's toString() adds more text beyond what super.toString() returns.
(C) The constructor passes "Truck" as the type, not "Vehicle".
(D) toString() returns the full formatted string, not just the tons value.
Common Mistake
super.toString() calls the parent class version, allowing the subclass to build upon the parent's output. This is a common pattern for building toString() in inheritance hierarchies.
AP Exam Tip
Using super.method() inside an overriding method lets you reuse parent logic. This avoids code duplication in toString() chains.