DEV Community

Hayes vincent
Hayes vincent

Posted on

super(Keyword in java)

** What is super keyword?**

  • super is a reference variable in Java.

  • It is used to refer to the immediate parent class object.
    Why super keyword is used?

We use super mainly for three purposes:

-To call parent class constructor
super() is used inside a child class constructor to call the parent’s constructor.

-To access parent class variables
If child and parent have same variable names, we can use super.variableName to access the parent’s variable.

-To access parent class methods
If child overrides a parent method, we can call the parent’s method using super.methodName()
Enter fullscreen mode Exit fullscreen mode

When super is used?

  • Inside a constructor (to call parent’s constructor).

  • Inside a method (to call parent’s variable or parent’s method).

  • When there is overriding or same variable names in parent and child.

class Parent {
    void show() {
        System.out.println("Parent show()");
    }
}

class Child extends Parent {
    void show() {
        super.show(); // Calls parent method
        System.out.println("Child show()");
    }
}


**output:**
Parent show()
Child show()

Enter fullscreen mode Exit fullscreen mode

Top comments (0)