Unit 3 Cycle 2 Day 14: Inheritance: Multi-Level Override
Share
Inheritance: Multi-Level Override
Section 3.13 — Overriding Methods
Key Concept
Multi-level method overriding occurs when a method is overridden at multiple levels of an inheritance chain. If A defines m(), B extends A overrides m(), and C extends B also overrides m(), then calling m() on a C object always executes C's version. If C does not override but B does, B's version runs. The AP exam traces these chains by asking what output is produced when different objects in the hierarchy respond to the same method call.
Consider the following classes.
What does new Z().val() return?
Answer: (C) 12
Z's val() calls super.val(), which is Y's val() (the direct parent). Y's val() returns 2. Z's val() returns 2 + 10 = 12.
Why Not the Others?
(A) super refers to Y (direct parent), not X (grandparent). Y returns 2.
(B) 11 = 1+10, which would be the case if super referred to X. But super refers to Y.
(D) 10 would mean super.val() returned 0, but Y's val() returns 2.
Common Mistake
super always refers to the direct parent class. Z's super.val() calls Y's version, not X's. There is no way to skip levels with super.
AP Exam Tip
super goes exactly one level up. In a multi-level hierarchy A->B->C, C's super refers to B only. To call A's version from C, B would need to use super itself.