Java super Keyword with Example
Java super Keyword
In this tutorial, we will learn about the super keyword in Java. In the previous post, we learned about this keyword.
In Java, the super
keyword is used to refer to the parent (superclass) object. super is a reference variable that points to the superclass object. We can use this keyword in a subclass to refer to the parent methods, variables, and constructors.
Access parent class methods โ
You can call a method of the superclass that has been overridden in the subclass.
Access parent class variables โ
When the child class has a variable with the same name, super
helps to access the superclass variable.
Call parent class constructor โsuper()
is used to invoke the parent class constructor. It must be the first statement inside the subclass constructor.
Example
Example to demonstrate the keyword is as follows:
// Constructor public class SalaryEmployee extends Staff { private double empSalary; //Constructor public SalaryEmployee(String name, String address, double salary) { super(name, address); this.empSalary = salary; } }
Notice how we have invoked the Parent class constructor using the super keyword.
super(name, address);
The super
keyword in Java is used to access parent class members (methods, variables, constructors) from a subclass.
—
Java Tutorial on this website: