Understanding the super
Keyword in Java
When working with inheritance in Java, super
keyword plays key role in accessing members (variables, methods, and constructors) of parent class. It helps avoid confusion when subclass and superclass share similar names for methods or variables.
What is super
in Java?
In Java, super
is reference variable used to refer to immediate parent class object. Whenever you create an instance of subclass, an instance of its superclass is also created, and super
points to it.
Common Uses of super
in Java
Java allows you to use the super
keyword in three main ways:
1. Accessing Parent Class Variables
If subclass has a variable with the same name as the parent class, use super
to refer to the parent’s variable.
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void display() {
System.out.println("Child x: " + x);
System.out.println("Parent x: " + super.x);
}
}
2. Calling Parent Class Methods
If method is overridden in the subclass, you can still access the parent class version using super
.
class Parent {
void show() {
System.out.println("This is Parent");
}
}
class Child extends Parent {
void show() {
System.out.println("This is Child");
super.show(); // Call parent method
}
}
3. Invoking Parent Class Constructor
Use super()
to call the constructor of the parent class. It must be the first statement in the child class constructor.
class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
Child() {
super(); // Must be first
System.out.println("Child Constructor");
}
}
Top comments (0)