Video in progress

When is the super keyword used?

super refers to the parent class: super(...) calls the parent constructor (it must be the first line of the constructor), super.method() calls the overridden parent method, and super.field accesses a hidden parent field.

📖 Answer

Let's look at the two main cases in one example:

class Shape {
    protected String name;
    Shape(String name) { this.name = name; }
    String describe() { return "Shakl: " + name; }
}

class Circle extends Shape {
    private final double r;

    Circle(double r) {
        super("doira");                 // 1) the parent constructor
        this.r = r;
    }

    @Override
    String describe() {
        return super.describe() + ", r=" + r;   // 2) the parent method + something extra
    }
}

Interviewers often ask about these points:

  • If you don't write super(...) in a constructor, the compiler adds super() automatically. If the parent has no no-argument constructor, it is a compile error.
  • super(...) and this(...) can't be used together, because both must be on the first line.
  • There is no such thing as super.super.method(); you can only refer to the direct parent.
  • You can't use super in a static context.