Wednesday , December 12 2018
Home / Java / Super keyword in java

Super keyword in java

Super keyword in java is a reference variable that is used to refer parent class object.Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.

Usage of java super Keyword

  1. super is used to refer immediate parent class instance variable.
  2. super() is used to invoke immediate parent class constructor.
  3. super is used to invoke immediate parent class method.

1) super is used to refer immediate parent class instance variable.

In the above program we have the same variable “num” declared in both parent class and sub class. There is no way we can access the num variable of parent class without using super keyword.

Accessing the num variable of parent class:

As you can see by using super.num we accessed the num variable of parent class.

2) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor as given below:

3) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below:

In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method.
Program in case super is not required

 

 

About admin

Check Also

Internal Working of HashMap in Java

In this article, we will see how hashmap’s get and put method works internally. What ...

Leave a Reply