The
super keyword in Java is a reference variable that is used to refer to the immediate parent class object. It is used in three scenarios:
Referencing Parent Class Instance Variables:
If a subclass (derived class) contains the same variables as the parent class (base class), super can be used to refer to the variable from the parent class.
Referencing Parent Class Instance Variables using super keyword example
class Vehicle {
int maxSpeed = 120;
}
class Car extends Vehicle {
int maxSpeed = 180;
void display() {
System.out.println("Maximum Speed: " + super.maxSpeed); // prints maxSpeed of Vehicle class
}
}
public class Main{
public static void main(String args[]){
Car obj=new Car();
obj.display();
}
}
Output
Maximum Speed: 120
In this example, super.maxSpeed refers to the maxSpeed of the Vehicle class, not the Car class.
Invoking Parent Class Methods:
If a subclass has the same method as the parent class, super can be used to invoke the method from the parent class.
Invoking Parent Class Methods using super keyword example
class Car {
void run() {
System.out.println("Running...");
}
}
class Engine extends Car {
void run() {
System.out.println("Engine Started...");
}
void work() {
super.run(); // calls run() method of Car class
run();
}
}
public class Main{
public static void main(String args[]){
Engine obj=new Engine();
obj.work();
}
}
Output
Running...
Engine Started...
In this example, super.run() calls the run() method of the Car class, not the Engine class.
Invoking Parent Class Constructor:
super() is used to call the constructor of the parent class.
Invoking Parent Class Constructor using super keyword
class Animal {
Animal() {
System.out.println("animal is created");
}
}
class Dog extends Animal {
Dog() {
super();
System.out.println("dog is created");
}
}
public class Main{
public static void main(String args[]){
Dog obj=new Dog();
}
}
Output
animal is created
dog is created
In this example, super() is used in the Dog class constructor to call the Animal class constructor.
Note: super() is added in each class constructor automatically by the compiler if there is no super() or this(). If there is no constructor, the compiler also adds a default constructor.