There are 3 ways in which we can use the keyword super in Java:
- Invoking a superclass method from a subclass,
- Using a superclass field in a subclass,
- Calling a superclass constructor.
1. Invoking a superclass method from a subclass
We can call the method from the superclass by placing the super keyword before the method call:
class Vehicle {
void startEngine() {
System.out.println("Starting the engine...");
}
void stopEngine() {
System.out.println("Stopping the engine...");
}
}
class Car extends Vehicle {
void move() {
System.out.println("The car is moving...");
}
void invoke() {
super.startEngine();
move();
super.stopEngine();
}
}
class TestSuper2 {
public static void main(String args[]){
Car car = new Car();
car.invoke();
}
}
Output: Starting the engine… The car is moving… Stopping the engine…
2. Using a superclass field in a subclass
We use the super keyword to reference a field of the superclass in a subclass.
class Vehicle {
public int maxSpeed;
}
class Car extends Vehicle {
void setMaxSpeed(int maxSpeed) {
super.maxSpeed = maxSpeed;
}
int getMaxSpeed() {
return super.maxSpeed;
}
}
class Test {
public static void main(String args[]) {
Car car = new Car();
car.setMaxSpeed(250);
System.out.println(car.getMaxSpeed());
}
}
Output: 250
3. Calling a superclass constructor
We can also call a constructor from the superclass from the subclass constructor.
class Vehicle {
Vehicle() {
System.out.println("Vehicle is created");
}
}
class Car extends Vehicle {
Car() {
super();
System.out.println("Car is created");
}
}
class Test {
public static void main(String args[]){
Car car = new Car();
}
}
Output: Vehicle is created Car is created
If we don’t add the super keyword to the subclass constructor ourselves, the compiler will add it. So whenever we call a subclass constructor, the corresponding superclass constructor will be called first.
Note: Call to ‘super()‘ must be the first statement in the constructor’s body; otherwise, we’ll get a compiler error:
class Car extends Vehicle {
Car() {
System.out.println("Car is created");
super(); // compiler error
}
}
I hope this tutorial was helpful to you. To learn more, check out Java Tutorials for Beginners page.
Happy learning!