Table of content

What is super in Java?

The super keyword is a reference variable used to refer to parent class(super class) objects. The super keyword came into existence with the concept of inheritance.

The super keyword can be used to

  • To call parent class methods.
  • To access parent class constructor.
  • To access attributes of the parent class.

The methods of parent class and child class can have same name. To differentiate among these methods, the super keyword can be used. The super keyword refers the parent class method.

Let us look into an example where there is a method with same name in the parent class and child class. The super keyword calls the parent class method.

class Vehicle {
  public void display() {
    System.out.println("This is parent class.");
  }
}
class Car extends Vehicle {
  public void display() {
    System.out.println("This is child class.");
  }
  public void printMessage() {
    display(); // calling the child class method display()
    super.display(); // calling the parent class method display()
  }
}
class Demo {
  public static void main(String[] args) {
    Car obj = new Car();
    obj.printMessage();
  }
}

The output is

This is child class.
This is parent class.

Let us look into example where both parent class and child class have the same attribute name type. The super keyword accesses the attribute type of parent class Vehicle.

class Vehicle {
  String type = "Electric car";
}
class Car extends Vehicle {
  String type = "Diesel car";
  void printType() {
    //prints type of child class 
    System.out.println("The car in child class is: " + type);  
    //prints type of parent  class  
    System.out.println("The car in parent class is: " + super.type); 
}
class Example {
  public static void main(String args[]) {
    Car obj = new Car();
    obj.printType();
  }
}

The output is

The car in child class is: Diesel car
The car in parent class is: Electric car

Let us look into an example of invoking a parent class constructor using super keyword. The parent class constructor can explicitly be called from child class using super(). The super() is a special form of the super keyword.

class Vehicle {
  Vehicle() {
    System.out.println("Constructor of parent class.");
  }
}
class Car extends Vehicle {
  Car() {
    super(); // calling constructor of parent class
    System.out.println("Constructor of child class.");
  }
}
class Test {
  public static void main(String args[]) {
    Car c = new Car(); // default constructor Car is called
  }
}

The output is

Constructor of parent class.
Constructor of child class.
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions