The super Keyword

Three Uses of super

  • super(...): call the parent constructor (must be the first line of the child constructor).
  • super.method(): call the parent version of an overridden method.
  • super.field: access a parent field hidden by a child field with the same name.

super() and super.method()

Example

public class Main {
    public static void main(String[] args) {
        Manager m = new Manager("Priya", 80000, 20000);
        m.describe();
        System.out.println("Pay: " + m.monthlyPay());
    }
}

class Employee {
    String name;
    double salary;

    Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
        System.out.println("Employee constructor");
    }

    double monthlyPay() {
        return salary;
    }

    void describe() {
        System.out.println("Employee: " + name);
    }
}

class Manager extends Employee {
    double bonus;

    Manager(String name, double salary, double bonus) {
        super(name, salary);          // parent sets name and salary
        this.bonus = bonus;
        System.out.println("Manager constructor");
    }

    @Override
    double monthlyPay() {
        return super.monthlyPay() + bonus;   // reuse parent logic
    }

    @Override
    void describe() {
        super.describe();
        System.out.println("Role: Manager");
    }
}

Output

Employee constructor
Manager constructor
Employee: Priya
Role: Manager
Pay: 100000.0

Implicit super()

If a child constructor does not call super(...), Java inserts super() (no arguments) automatically. If the parent has no no-argument constructor, you get a compile error.

class Parent {
    Parent(String name) { }
}

class Child extends Parent {
    Child() { }   // error: constructor Parent in class Parent cannot be applied to given types
}