Super Keyword

Filter Course


Super Keyword

Published by: Dikshya

Published date: 26 Jun 2023

Super Keyword

The super keyword in object-oriented programming is used to refer to the superclass, allowing access to its members (fields, methods, and constructors) from within the subclass. It is primarily used in the context of inheritance to differentiate between superclass members and subclass members with the same name.

Accessing Superclass Members: In a subclass, you can use super to access and invoke the superclass's members, including fields and methods that are not overridden in the subclass. This is especially useful when you want to use or override the superclass behavior while adding new functionality in the subclass.

Example:

public class Superclass {
    protected int value;

    public void display() {
        System.out.println("Superclass: " + value);
    }
}

public class Subclass extends Superclass {
    private int value;

    public Subclass(int value) {
        super.value = value; // Accessing the superclass field
    }

    @Override
    public void display() {
        super.display(); // Invoking the superclass method
        System.out.println("Subclass: " + value);
    }
}

In the above example, the super.value statement is used to access the value field of the superclass from the constructor of the subclass. Similarly, super.display() is used to invoke the display() method of the superclass from the overridden display() method in the subclass.

Invoking Superclass Constructors:

When a subclass constructor is called, it can use super to invoke a constructor in the superclass. This allows for proper initialization of inherited members in the superclass before the subclass performs its own initialization.

Example:

public class Superclass {
    protected int value;

    public Superclass(int value) {
        this.value = value;
    }
}

public class Subclass extends Superclass {
    private String name;

    public Subclass(int value, String name) {
        super(value); // Calling the superclass constructor
        this.name = name;
    }
}

In the above example, the super(value) statement is used in the constructor of the subclass to call the parameterized constructor of the superclass. This ensures that the value field of the superclass is properly initialized before the subclass proceeds with its own initialization.

The super keyword is an essential tool when working with inheritance, allowing you to access superclass members and invoke superclass constructors from within the subclass. It helps in code reuse, provides a clear distinction between superclass and subclass members, and ensures proper initialization in the inheritance hierarchy.