Super Keyword in Java

Super keyword is associated with the Inheritance in Java. super keyword which refers to the immediate parent of a class. In Java whenever you create the instance of the subclass, an instance of the parent class is created implicitly.

 

Uses of Super

  • Call immediate parent class constructor using super()
  • Call immediate parent class method using super
  • Call parent class variables using super keyword

 

Use super() to call super class Constructor

Super() is used to instantiate the immediate parent class constructors. We have seen, When we create the object of the subclass, first, the constructor of parent class gets invoked implicitly and then the constructor of child class then what is the use of super()?

Here the point to be noted that, implicitly a default constructor of the superclass is called not a parameterized one. To call a parameterized constructor of a superclass we must use ‘super(parameters..)‘ with matching parameters.

Output:

Employee Name is Merrilla and Employee id is SEL-250612

 

Video Tutorial in Automation Testing:

 

Use super to call super class Method

super.method_name calls Overridden method. It should be used in case subclass contains the same method as the parent class. We can understand this with below example-

Output:

Hello I am from Super class
Hi I am from child class

 

Use super to call super class Variables

In Java, super keyword can be used to refer superclass instance in a subclass. In the below example we are taking only one variable ‘name’ and calling this variable in the subclass using super keyword.

Output:

Super class varaible is Car
Subclass variable is Audi

 

0 Comment

Leave a Reply