Super keyword in Java with uses and examples

What is Super keyword in Java

A Super keyword in java is a keyword used to access immediate parent class instance variable, methods and constructors.

java super keyword used in classes where inheritance hierarchy exists.

Uses of super keyword in Java

In Java super keyword is used when a sub class wants to refer its immediate super (parent) class instance variable, methods and constructors then super keyword can used to access them.

  1. To access parent class hidden instance variable.
  2. To call parent class overridden method.
  3. To call the parent class constructor in java.

A. To access parent class hidden instance variable using super keyword.

In java programming, when a super class and sub class both has a instance variable that has a same name.

Then instance variable of sub class hides it’s super class instance variable.

This problem is known as Instance variable hiding.

We can solve the problem of Instance variable hiding, by using super keyword.

Here base class and child class both contains instance variable i. Value of i is different for both classes.

Here i refers to class Two’s instance variable.

To access class one’s i here super.i is used.

B. To call parent class overridden method using super keyword

In Java programming, when sub class have same method signature and return type as parent has then the method is known as overridden method.

If case of overridden method child class can not access parent class overridden method directly.

If want to access the super class overridden method, then super keyword is used.

Description:  When  triangle.show();  call area().

area() calls Triangle class area().

To call Shape class area(). Include super keyword as super.area()

C. To call the parent class constructor using super keyword in java

In java programming, to call immediate parent class constructor super() can be used.

Parent class constructor must be called from child class constructor and must be first line in constructor call.

syntax to call constructor

super()//call default constructor
super(3,3) //call two integer argument constructor

Note: Call to super class constructor must appears as the first statement with in the sub class.

Description:  When super(i,j); line will execute. super( i, j ) will call it’s immediate super class  A’s constructor. 

Another Example with use of constructor call using super and use of this keyword.

Output