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: super.variableName
Let’s see this with the help of example.

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

Calling Person constructor
Calling Employee class constructor
Printing default name from person class : Default

As you can see, we have used super.name to print name from the parent class in Employee class.

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 constructor
Calling Employee class constructor
Employee’s name:John

As you can see we have used super keyword to call Person constructor 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 constructor
Calling Employee class constructor
Printing default name from person class : Default
Printing 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

Add Comment