super Keyword in Java

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:

  1. Access Parent Class Methods – Call overridden methods from the superclass.
  2. Invoke Parent Class Constructor – Use super() to call the parent class constructor.
  3. 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.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments