The super
keyword in Java is a powerful tool that allows you to access members of a parent class from within a subclass. It essentially acts as a bridge between the child and parent classes, enabling you to leverage the functionality inherited from the parent.
How does super
work?
- Accessing Parent Class Members: When used with member variables,
super
allows you to directly access the parent class's version of a variable, even if the subclass has overridden it. - Calling Parent Class Methods: You can use
super
to call the parent class's version of a method, even if the subclass has overridden it. This is useful for preserving parent class behavior while extending it in the subclass. - Constructor Chaining: In the constructor of a subclass, you can use
super
to explicitly call the constructor of the parent class. This is essential for initializing the inherited members from the parent class.
Examples:
1. Accessing Parent Class Variable:
class Parent {
int value = 10;
}
class Child extends Parent {
int value = 20;
void display() {
System.out.println("Child value: " + value);
System.out.println("Parent value: " + super.value);
}
}
In this example, the super.value
call retrieves the value of the value
variable from the Parent
class.
2. Calling Parent Class Method:
class Parent {
void display() {
System.out.println("Parent method called");
}
}
class Child extends Parent {
@Override
void display() {
super.display();
System.out.println("Child method called");
}
}
Here, super.display()
calls the display()
method of the Parent
class before executing the code in the Child
's display()
method.
3. Constructor Chaining:
class Parent {
Parent() {
System.out.println("Parent constructor called");
}
}
class Child extends Parent {
Child() {
super(); // Calling the parent constructor
System.out.println("Child constructor called");
}
}
This code demonstrates how super()
is used within the child constructor to call the parent constructor, ensuring that the parent class is initialized correctly.
Conclusion:
The super
keyword in Java is an important tool for working with inheritance. It provides a way to access and utilize functionality from parent classes within subclasses, allowing for more flexible and powerful object-oriented programming.