Super keyword in java with example

Previous
Next

Super Keyword in java is used to refer to object of the immediate superclass.Super keyword is used in the context of inheritance.
Super keyword in java can be used at three level:

  • Variable level
  • Constructor level
  • Method level

Usage of super at variable level:

We can refer to variable of super class using:

Let’s see this with the help of example.

When you run above program, you will get below output:

Calling Person constructorCalling Employee class constructorPrinting default name from person class : Default

As you can see, we have used super.name to print name from parent class in Employee class.
Usage of super at Constructor level:
super keyword can be used to call the constructor of parent class.Please note that super should be first statement in child class constructor.
Let’s see with the help of example:

When you run above program, you will get below output:

Calling Person Parameterized constructorCalling Employee class constructorEmployee’s name:John

As you can see we have used super keyword to call Person contructor from employee class.
Usage of super keyword at method level:
Super keyword can be used to call method of Parent class. It can be used to specifically call method of parent class in case of method overriding.
Let’s see with the help of example:

When you run above program, you will get below output:

Calling Person constructorCalling Employee class constructorPrinting default name from person class : DefaultPrinting name from Employee class : Martin

As you can see, we have called Person class method from Employee class using super keyword.That’s all about super keyword in java.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog