DEV Community

MANIKANDAN
MANIKANDAN

Posted on

Super Keyword in Java

The super keyword in Java is used to refer to the immediate parent class object. It is commonly used to access parent class methods and constructors, enabling a subclass to inherit and reuse the functionality of its superclass.

The super keyword refers to superclass (parent) objects.

It is used to call superclass methods and to access the superclass constructor.

The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

To understand the super keyword, you should have a basic understanding of Inheritance and Polymorphism.

  1. Use of super with Variables ?

This scenario occurs when a derived class and base class have the same data members. In that case, there is a possibility of ambiguity for the JVM.


class Vehicle {
    int maxSpeed = 120;
}

class Car extends Vehicle {
    int maxSpeed = 180;

    void display()
    {
        System.out.println("Maximum Speed: "
                           + super.maxSpeed);
    }
}


class Test {
    public static void main(String[] args)
    {
        Car small = new Car();
        small.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Maximum Speed: 120

  1. Use of super with Methods

This is used when we want to call the parent class method. So, whenever a parent and child class have the same-named methods, then to resolve ambiguity, we use the super keyword.


class Person {
    void message()
    {
        System.out.println("This is person class\n");
    }
}


class Student extends Person {
    void message()
    {
        System.out.println("This is student class");
    }


    void display()
    {

        message();

        super.message();
    }
}


class Test {
    public static void main(String args[])
    {
        Student s = new Student();
        s.display();
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Use of super with Constructors

The super keyword can also be used to access the parent class constructor. One more important thing is that ‘super’ can call both parametric as well as non-parametric constructors depending on the situation.

class Person {
    Person()
    {
        System.out.println("Person class Constructor");
    }
}

class Student extends Person {
    Student()
    {
        super();

        System.out.println("Student class Constructor");
    }
}

class Test {
    public static void main(String[] args)
    {
        Student s = new Student();
    }
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)