Unit 3 Cycle 2 Day 8: Polymorphism with toString

Unit 3 Advanced (Cycle 2) Day 8 of 28 Advanced

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.

public class Vehicle { private String type; public Vehicle(String t) { type = t; } public String toString() { return type; } } public class Truck extends Vehicle { private int tons; public Truck(int t) { super("Truck"); tons = t; } public String toString() { return super.toString() + " (" + tons + "T)"; } }

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.

Review this topic: Section 3.16 — Object Superclass • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.