Unit 3 Cycle 1 Day 27: Inheritance Hierarchy Tracing
Share
Inheritance Hierarchy Tracing
Section Mixed — Review: Inheritance
Key Concept
Inheritance hierarchy tracing involves following execution through multiple levels of superclass-subclass relationships. When three or more classes form a chain (e.g., Object → Vehicle → Car → Sedan), method resolution starts at the runtime type and moves up until a matching method is found. Constructor execution moves down from the top. The AP exam tests deep hierarchies where the answer depends on correctly identifying which class provides the method that actually executes.
Consider the following classes.
What does new C().show() return?
Answer: (B) "B"
C does not override show(). Java looks up the inheritance chain: C has no show(), B has show() returning "B". B's version is used.
Why Not the Others?
(A) B overrides A's show(). Java finds B's version before reaching A.
(C) C does not define show(), so there is no "C" to return.
(D) C inherits show() from B. No compile error.
Common Mistake
When a method is not overridden in the current class, Java searches up the inheritance chain. It uses the first matching method found, which is B's in this case.
AP Exam Tip
Method resolution goes up the hierarchy: check the class, then parent, then grandparent. The first found match is used.