Super keyword in java with example (JNNC Technologies)


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.

Post a Comment

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();