Super keyword in Java with examples

Hello everyone, in this tutorial, we will talk about the super keyword in Java. The super keyword in Java is used as a reference variable. It can be used to refer to the parent class object. We will see some Java Programs involving the use of the super keyword.

There are different use of super keyword in Java. Let’s try to understand each of them separately.

To refer the data members of the parent class

Suppose, we have a parent class and its derived class that have variables with the same name. In such cases, we can use the super keyword to tell the JVM that the variable that we want to use is the variable of the parent class. The following example program will help you understand the concept.

import java.io.*;

class Parent{
    int var = 10;
}

class Child extends Parent{
    int var = 100;
    void fun(){
        System.out.println("var(child) is " + var);
        System.out.println("var(parent) is " + super.var);
    }
}

class Example{
  public static void main (String[] args) {
      Child c = new Child();
      c.fun();
  }
}

Output:

var(child) is 100
var(parent) is 10

To invoke the methods of the parent class

In the context of inheritance, whenever a child class and the parent class have a method with the same name, we can use the super keyword to specify the parent class method. Have a look at the below example program and the output.

import java.io.*;

class Parent{
    void fun1(){
        System.out.println("Parent.");
    }
}

class Child extends Parent{
    void fun1(){
        System.out.println("Child.");
    }
    
    void fun2(){
        fun1();
        super.fun1();
    }
}

class Example{
  public static void main (String[] args) {
      Child c = new Child();
      c.fun2();
  }
}

Output:

Child.
Parent.

To invoke the constructor of the parent class

The super keyword can also be used in order to access the constructor of the parent class. See the below example program to understand how it can be done.

import java.io.*;

class Parent{
    Parent(){
        System.out.println("Parent.");
    }
}

class Child extends Parent{
    Child(){
        super();
        System.out.println("Child.");
    }
}

class Example{
  public static void main (String[] args) {
      Child c = new Child();
  }
}

Output:

Parent.
Child.

In the above example, we have used super() to make a call to the parent class constructor in the child class constructor.

Few Points to remember:

  • While calling the parent class constructor through a child class constructor, the super() statement must be the first statement in the child class constructor.
  • super() is added ( as the first statement) in a child class constructor automatically by the compiler even if we don’t use super().

Thank you.

Also read: What Is Inheritance In Java?

Leave a Reply

Your email address will not be published. Required fields are marked *