Card 06/ 10
All 10 cards
ConceptDifficulty: Intermediate1 min
What super Reaches, and the Call the Compiler Writes for You
An overriding method that needs to do everything the parent did, and then one thing more. Calling the method by name calls itself, and the program runs out of stack.
class PremiumCustomer extends Customer {
@Override
String label() {
return super.label() + " (premium)";
}
}super.label() reaches past the override to the parent's version of the method. It is the only way to get at a body your own class has replaced, and it works for one level up rather than for any ancestor — there is no super.super.
| Written | Means | Where it may appear |
|---|---|---|
super.method() | The parent's version of this method | Anywhere in an instance method |
super(...) | The parent's constructor | The first statement of a constructor, and nowhere else |
The second form is the one you mostly do not write. Every constructor must start by running a parent constructor, so when you write neither super(...) nor this(...) the compiler inserts super(); for you.
So the useful thing to hold is that every object is built from the top down whether or not the word super appears in your source — and the error you get when a parent has no no-argument constructor is that hidden line becoming visible.