EMZETT.
Login

super Keyword

In short: A reference to the superclass within a subclass — either calls the superclass’s constructor (super(...)) or accesses a method it overrides (super.method()).

In more detail: super(...), if used, must be the very first line in the subclass’s constructor. Without an explicit call, Java automatically calls the superclass’s parameterless constructor — if the superclass has no such constructor, a compile error occurs, forcing an explicit super(...).

In Depth

class Vehicle {
    protected int speed;
 
    Vehicle(int speed) {
        this.speed = speed;
    }
 
    void info() { System.out.println("Vehicle at " + speed + " km/h"); }
}
 
class Car extends Vehicle {
    Car(int speed) {
        super(speed); // calls Vehicle(int) - MUST be the first line
    }
 
    @Override
    void info() {
        super.info(); // additionally calls the OVERRIDDEN version from Vehicle
        System.out.println("...and is a car");
    }
}

super has two different uses that are easily confused: super(...) (with parentheses) calls a constructor of the superclass and may only appear as the first statement in a constructor. super.method() (with no parentheses right after the dot), by contrast, calls the version of a method as implemented in the superclass — useful when you want to override a method (@Override) but not completely replace the superclass’s behaviour, only ADD to it (as in the info() example above).

If a subclass constructor omits super(...) entirely, the compiler automatically inserts an invisible call to the superclass’s parameterless constructor. But if the superclass has no parameterless constructor at all (e.g. because only Vehicle(int) exists, as above), a compile error forces you to explicitly call super(...) with matching arguments.

See also: Inheritance, this Keyword, Constructors