Super Keyword in Java

The super keyword in Java is used to refer to the immediate parent class of an object. It serves two primary purposes: accessing superclass methods and variables, and calling the superclass constructor. This mechanism facilitates inheritance, allowing subclasses to inherit properties and behaviors from their parent classes.

Key Points on Super Keyword:

Syntax of Super Keyword:

Syntax Example

class Parent {
    int value = 10;

    Parent() {
        System.out.println("Parent Constructor");
    }

    void display() {
        System.out.println("Value from Parent: " + value);
    }
}

class Child extends Parent {
    int value = 20;

    Child() {
        super(); // Call Parent constructor
        System.out.println("Child Constructor");
    }

    void display() {
        super.display(); // Call Parent display method
        System.out.println("Value from Child: " + value);
    }
}

Example of Super Keyword in Java:

This example demonstrates the use of the super keyword to access parent class methods and variables.

Code Example: Super Keyword

public class Parent {
    int value = 10;

    Parent() {
        System.out.println("Parent Constructor");
    }

    void display() {
        System.out.println("Value from Parent: " + value);
    }
}

public class Child extends Parent {
    int value = 20;

    Child() {
        super(); // Call Parent constructor
        System.out.println("Child Constructor");
    }

    void display() {
        super.display(); // Call Parent display method
        System.out.println("Value from Child: " + value);
    }

    public static void main(String[] args) {
        Child child = new Child(); // Create instance of Child
        child.display(); // Call display method
    }
}

Output

Parent Constructor
Child Constructor
Value from Parent: 10
Value from Child: 20

Detailed Explanation:

Understanding the super keyword is vital for leveraging inheritance in Java effectively. It helps maintain a clean code structure, promotes code reusability, and enhances clarity in method and constructor calls.