When is the super keyword used?
In Java, the super keyword is a reference variable that is used to refer to the immediate parent class objects. Whenever the instance of a subclass is created, an instance of parent class is also implicitly created. The super reference variable refers to this parent class.
The super keyword can be used in the following manner:
- It can be used to refer to the immediate parent class instance variable. Here the super keyword is used to access the data member or field of parent class. However, the parent class and child class should have same fields.
- It can be used to invoke the immediate parent class method. It can only be used if the subclass contains the same method as the parent class. It should be used if the method is overridden.
- It can also be used to invoke the immediate parent class constructor. The super keyword can call both parametric as well as non-parametric constructors depending upon the situation.