Unit 3 Cycle 2 Day 17: Inheritance: super in toString
Share
Inheritance: super in toString
Section 3.14 — The super Keyword
Key Concept
When overriding toString() in a subclass, calling super.toString() includes the superclass's representation in the result. The pattern return super.toString() + ", extra: " + extraField builds on the parent's output. If the superclass also overrides toString() with its own super.toString() call, the result chains through the hierarchy. The AP exam tests this by tracing toString() calls that cascade through multiple levels, producing concatenated output from each level.
Consider the following classes.
What does System.out.println(new Pet("Max", "Jo")); print?
Answer: (B) Max (Owner: Jo)
Pet's toString(): super.toString() returns "Max" (Animal's version). Appends " (Owner: Jo)". Full result: "Max (Owner: Jo)".
Why Not the Others?
(A) Pet's toString() adds owner information beyond the name.
(C) Both classes override toString(), so the default Object format is not used.
(D) The full string includes the name and owner, not just the owner.
Common Mistake
super.toString() reuses parent logic. The subclass extends the output rather than duplicating the parent's code.
AP Exam Tip
Building toString() with super.toString() is a clean inheritance pattern. It avoids accessing private parent fields directly.