What is the super keyword in Java?

The super keyword in Java is a reference variable used to refer to the immediate parent class object. It serves several purposes in inheritance, allowing subclasses to access or invoke the members (methods, constructors, and variables) of their parent class.

Uses of the super Keyword

1. Accessing Parent Class Variables:

  • The super keyword can be used to differentiate between the instance variables of the parent class and the subclass when they have the same name.
  • Example:

```java

class Parent {

int number \= 10;

}

class Child extends Parent {

int number \= 20;

   void display() {
       System.out.println("Child number: " + number); // Refers to the subclass variable
       System.out.println("Parent number: " + super.number); // Refers to the parent class variable
   }

}

public class Main {

public static void main(String[] args) {

Child child \= new Child();

child.display();

}

}

**Output**:

Child number: 20

Parent number: 10

```

2. Calling Parent Class Methods:

  • The super keyword can be used to call methods of the parent class from the subclass when the subclass has overridden the parent class methods.
  • Example:

```java

class Parent {

void show() {

System.out.println("Parent class method");

}

}

class Child extends Parent {

void show() {

System.out.println("Child class method");

}

   void display() {
       super.show(); // Calls the parent class method
       show();       // Calls the subclass method
   }

}

public class Main {

public static void main(String[] args) {

Child child \= new Child();

child.display();

}

}

**Output**:

Parent class method

Child class method

```

3. Calling Parent Class Constructors:

  • The super keyword can also be used to invoke the constructor of the parent class from the subclass. This must be the first statement in the subclass constructor.
  • Example:

```java

class Parent {

Parent() {

System.out.println("Parent class constructor");

}

}

class Child extends Parent {

Child() {

super(); // Calls the parent class constructor

System.out.println("Child class constructor");

}

}

public class Main {

public static void main(String[] args) {

Child child \= new Child();

}

}

**Output**:

Parent class constructor

Child class constructor

```


Summary of super Keyword

  • Purpose: The super keyword is used to access members (variables, methods, constructors) of the parent class from the subclass.
  • Main Uses:
  • To access a parent class variable when it is hidden by a subclass variable.
  • To call a parent class method when it is overridden in the subclass.
  • To invoke a parent class constructor from a subclass constructor.
  • Important Note: When used to call a parent constructor, super() must be the first statement in the subclass constructor.