The super
keyword in Java is used to refer to the parent class. It plays a crucial role in inheritance by allowing subclasses to access methods, constructors, and properties of their superclass.
Key Uses of super
in Java:
- Access Parent Class Methods – Call overridden methods from the superclass.
- Invoke Parent Class Constructor – Use
super()
to call the parent class constructor. - Access Parent Class Variables – Refer to the superclass field when the subclass has the same field name.
Example:
class Parent {
String message = "Hello from Parent";
}
class Child extends Parent {
String message = "Hello from Child";
void display() {
System.out.println(super.message); // Access parent class variable
}
}
public class SuperExample {
public static void main(String[] args) {
Child obj = new Child();
obj.display(); // Output: Hello from Parent
}
}
The super
keyword ensures proper inheritance and method overriding. Mastering it improves code reusability and clarity.