what is super keyword in java with example

What is super keyword in java with example?

In Java, the super keyword is a reference variable used to refer to the immediate parent class object. It is used inside a subclass method or constructor to call a method or constructor of the superclass.

Here are the key uses of the super keyword:

1. Invoke Superclass Methods:
  • super can be used to invoke methods of the immediate parent class. If a subclass has a method with the same name as a method in its superclass, using super allows you to explicitly call the method from the superclass.

Java
/*
 * Author: Zameer Ali
 * */

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

class Child extends Parent {
    void display() {
        super.display(); // Calls the display() method of the Parent class
        System.out.println("Child class method");
    }
}

2. Invoke Superclass Constructor:
  • super is also used to call the constructor of the immediate parent class. This is particularly useful when the subclass constructor needs to perform additional tasks after calling the parent class constructor.

Java
/*
 * Author: Zameer Ali
 * */

class Parent {
    Parent(int x) {
        System.out.println("Parent class constructor with parameter: " + x);
    }
}

class Child extends Parent {
    Child() {
        super(10); // Calls the Parent class constructor with parameter
        System.out.println("Child class constructor");
    }
}

3. Access Parent Class Members:

  • super can also be used to access the data members of the parent class when they are hidden by the child class. This is often used when the child class has a variable with the same name as a variable in the parent class, and you need to access the parent class variable.

Java
/*
 * Author: Zameer Ali
 * */

class Parent {
    int x = 10;
}

class Child extends Parent {
    int x = 20;
    
    void display() {
        System.out.println(super.x); // Accesses the x variable of the Parent class
        System.out.println(this.x);   // Accesses the x variable of the Child class
    }
}

In summary, the super keyword in Java is used to differentiate between superclass and subclass members, allowing you to access or call the members of the immediate parent class in the context of the subclass.

Leave a Reply

Your email address will not be published. Required fields are marked *