Card 06/ 10

ConceptDifficulty: Intermediate1 min

The super Keyword: Parent Methods and Parent Constructors

An override that calls itself by name runs out of stack; super.label() reaches the parent's version.

super.method() calls the parent's version of a method your class has overridden, and super(...) calls a parent constructor from the first line of your constructor. When you write neither super(...) nor this(...), the compiler inserts super(); 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:

java
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.

The two things super does
WrittenMeansWhere it may appear
super.method()The parent's version of this methodAnywhere in an instance method
super(...)The parent's constructorThe 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 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.