Last Updated: 06 March, 2023
In Java, the super keyword is a reference variable that is used to refer to the immediate parent class object. In inheritance, when the parent class and child class have members with the same name, then the super keyword solves the naming conflicts. The super keyword is used to refer to the parent class members.
In Java, when we create an instance of the child class, the JVM implicitly creates an instance of the parent class as well, which is referred to by the super reference variable.
The super keyword will only be used inside the child class, not in the parent class.
The super keyword is used for the following purposes in Java; let's see them below.
Example 1: To refer the immediate parent class variables
Output
Child class variable: Child
Parent class variable: Parent
Example 2: To refer the immediate parent class methods
Output
Child - display() method
Child - show() method
Parent - show() method
Child - show() method
Example 3: To call the immediate parent class constructor
Output
Parent class - Default constructor called
Child class - Default constructor
Parent class - Default constructor called
Child class - Parameterized constructor value: Test
Parent class - Parameterized constructor value: My Test Data
Child class - two Parameterized (int, int) constructor value: 10 20
Example 4: Call immediate parent class method in Multilevel Inheritance
Output
A - show() method called
B - show() method called
C - show() method called
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com