Java

How to use the super keyword in Java programming

Following are the uses of super keyword:

  1. To refer the immediate super class constructor
  2. To refer the immediate super class members

Refer super class constructor:




The super keyword can be used to invoke the constructor of its immediate super class and pass data to it. Syntax for doing so is given below:

super(parameters-list);

When writing the above statement inside the constructor of the derived class, it must be the first line. It is a mandatory requirement.

For understanding how this works, let’s consider our previous example:

In the above example you can see that the data in Student class is made private. We can still pass data from the derived class CSEStudent to its parent class Student using the super construct given below:

super(name, regdNo, age);

You can also see that the above statement is the only line inside the CSEStudent class constructor. If there were multiple lines, the above line must be the first line.

Refer super class members

Second use of super keyword (in sub class) is to access the hidden members of its immediate super class. To understand this let’s consider the following example:

In the above example we can see that we are using the super keyword in two places. First use is to display the value of variable x of the super class A using the following expression:

super.x

Second use was for calling the display() method of the super class A in the sub class B using the following construct:

super.display()

Take your time to comment on this article.

Leave a Comment