JOOPs Through Java
All lessons

Unit 4 · The Four Pillars in Depth · 7 min

The super keyword

`super` refers to the parent class. It calls the parent's constructor, fields or methods from inside the child.

Why this matters

When a child overrides a method or hides a field, super is the only way back to the parent version.

Example

Java
class Person {
    String name;

    Person(String name) {
        this.name = name;
        System.out.println("Person constructor");
    }

    void introduce() {
        System.out.println("I am a person named " + name);
    }
}

class Student extends Person {
    int rollNumber;

    Student(String name, int rollNumber) {
        super(name);                // must be the first statement
        this.rollNumber = rollNumber;
        System.out.println("Student constructor");
    }

    @Override
    void introduce() {
        super.introduce();          // call parent version first
        System.out.println("My roll number is " + rollNumber);
    }
}

public class Main {
    public static void main(String[] args) {
        new Student("Ananya Rao", 12).introduce();
    }
}

Output

Person constructor
Student constructor
I am a person named Ananya Rao
My roll number is 12

Step by step

  1. 1`super(name)` calls the Person constructor and must be the first line of the child constructor.
  2. 2The parent constructor always runs before the child constructor body.
  3. 3`super.introduce()` calls the parent version of an overridden method.
  4. 4Without super.introduce(), only the child version would run.

Key points

  • super() calls the parent constructor
  • super.method() calls the parent method
  • super() must be the first statement in a constructor
  • Parent constructor always runs first

Common mistakes

  • Putting super() after another statement
  • Using both this() and super() in the same constructor

Try it yourself

  • Add constructors to Vehicle and Car and chain them with super.
  • Override a method and call the parent version inside it.
Open the practice notebook