What is ‘super’ keyword in java? Explained with example.

 The “super” keyword in Java is used to refer to the immediate parent class of an object. It is typically used within the context of inheritance, where a subclass inherits properties and methods from its parent class.

The “super” keyword can be used in several ways in Java, but its most common usage is to invoke a parent class’s constructor or to access a parent class’s method or variable.

For example, consider the following classes:

class Parent {
int x = 10;
void display() {
System.out.println("Parent class");
}
} class Child extends Parent {
int x = 20;
void display() {
System.out.println("Child class");
}
void displayParent() {
System.out.println("Value of x in parent class: " + super.x);
super.display();
}
}

In this example, the Child class extends the Parent class and inherits its properties and methods. However, the Child class also declares its own version of the “x” variable and the “display” method, which overrides the parent class’s versions.

When the “displayParent” method is called on an object of the Child class, it uses the “super” keyword to access the “x” variable and the “display” method of the parent class. The output of calling the method would be “Value of x in parent class: 10” and “Parent class”

Output:

Value of x in parent class: 10
Parent class

The “super” keyword can also be used to invoke a parent class’s constructor. For example, consider the following classes:

class Parent {
Parent() {
System.out.println("Parent class constructor");
}
} class Child extends Parent {
Child() {
super();
System.out.println("Child class constructor");
}
}

In this example, the Child class’s constructor uses the “super” keyword to invoke the Parent class’s constructor. When an object of the Child class is created, it will first execute the Parent class’s constructor, then the Child class’s constructor. So the output will be “Parent class constructor” and “Child class constructor”

Output:

Parent class constructor
Child class constructor

In conclusion, the “super” keyword in Java is used to refer to the immediate parent class of an object, and it is typically used within the context of inheritance. The “super” keyword can be used to invoke a parent class’s constructor, or to access a parent class’s method or variable. It is a powerful tool that allows developers to access the functionality of parent classes within child classes.