Home » java » Java Super Keyword

Java Super Keyword

Whenever a sub class wants to refer its immediate super class it can do so by using of super.

Use of super keyword

  • Super calls the super class constructor
  • It solves the problem of name hiding.
  • Using super keyword we can access super class overridden method

Super calls the super class constructor

In java programming, when a super class and sub class both has a constructor  than super class constructor will not call. We can call such constructor by using super keyword.

Super call the immediate super class 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. 

Solves the problem of name hiding using super

In java programming, when a super class and sub class both has a instance variable that has a same name then in the sub class,  instance variable of sub class hides it’s super class instance variable. This problem is known as name hiding problem.

We can solve the problem of name hiding by using super keyword.

Description: Superclass A and subclass B both have a variable i, then in the subclass B variable, i of the superclass cannot be accessed directly.

Subclass variable i hides its superclass variable i. Using “super.i” we can access the hidden variable i of super class A in subclass B.

Using super keyword we can access super class overridden method

In Java programming, when a super class and sub class both has a method that has Superclass same name and type signature than subclass method overrides its superclass method.

Such methods are called overridden method subclass and this process is said to be method overriding.

If we want to access the superclass overridden method, we can do so by using super keyword.

Description:  When  lineB.show(); “  will execute it will call sub class show().

Method show() of super class will overrides. Class A’s show() will never execute. But we can call super class show() method by using super keyword.

Here “ super.show();” will calls super class A’s overridden method.

Managed by MochaHost - Fast & Easy WordPress Hosting