Super Keyword in Java

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

Super can used in classes where inheritance exists.

Use of super keyword

  • To access parent class hidden instance variable.
  • To call parent class overridden method.
  • To call the parent class constructor.

To access parent class hidden instance variable.

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.

To call parent class overridden method

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

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()

To call the parent class constructor

In java programming, to call immediate parent class constructor super keyword 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