Explain ‘ super’ keyword in Java. What are the usage scenarios?
In Java, the super
keyword is a reference variable used to refer to the immediate parent class object. It serves several important purposes in the context of inheritance, allowing you to access members (fields and methods) of the parent class. Here are the primary usage scenarios for the super
keyword:
When a subclass overrides a method from its parent class, you can use super
to call the parent class's version of that method. This is useful when you want to extend the functionality of the parent method rather than completely replacing it.
Example:
class Parent {
void display() {
System.out.println("Display from Parent");
}
}
class Child extends Parent {
void display() {
super.display(); // Calls Parent's display method
System.out.println("Display from Child");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
Output:
Display from Parent
Display from Child
If a subclass has a field with the same name as a field in its parent class, you can use super
to refer to the parent class's field.
Example:
class Parent {
int value = 10;
}
class Child extends Parent {
int value = 20;
void display() {
System.out.println("Parent value: " + super.value); // Accesses Parent's value
System.out.println("Child value: " + value); // Accesses Child's value
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
Output:
Parent value: 10
Child value: 20
You can use super()
to call a constructor of the parent class. This is often done in the constructor of the child class to ensure that the parent class is properly initialized.
Example:
class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
Child() {
super(); // Calls Parent's constructor
System.out.println("Child Constructor");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
Output:
Parent Constructor
Child Constructor
You can also use super
to access static members of the parent class, although it's more common to access them directly using the class name.
Example:
class Parent {
static void staticMethod() {
System.out.println("Static method in Parent");
}
}
class Child extends Parent {
void display() {
super.staticMethod(); // Calls Parent's static method
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
Output:
Static method in Parent
The super
keyword is a powerful feature in Java that allows subclasses to interact with their parent classes. It is primarily used for:
Using super
appropriately helps maintain clear and manageable code in an inheritance hierarchy.