The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.
Whenever you create an instance of a subclass, an instance of the parent class is created implicitly, which is referred to by the super reference variable.
super Keywordsuper() can be used to call the parent class's constructor.One of the most common uses of super is to call the constructor of the parent class from the child class's constructor. This is essential when the parent class does not have a default (no-argument) constructor.
The call to super() must be the very first statement in the child class constructor.
class Vehicle {
String brand;
// Parent class constructor
public Vehicle(String brand) {
this.brand = brand;
System.out.println("Vehicle constructor called.");
}
public void displayBrand() {
System.out.println("Brand: " + brand);
}
}
class Car extends Vehicle {
String model;
// Child class constructor
public Car(String brand, String model) {
// Call the parent constructor using super()
super(brand);
this.model = model;
System.out.println("Car constructor called.");
}
public void displayModel() {
System.out.println("Model: " + model);
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of the subclass will call both constructors
Car myCar = new Car("Ford", "Mustang");
myCar.displayBrand();
myCar.displayModel();
}
}
In this example, super(brand) in the Car constructor calls the Vehicle(String brand) constructor, ensuring that the brand attribute from the parent class is properly initialized.
You can use super to call a method from the parent class, even if you have overridden it in the child class.
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
@Override
public void eat() {
super.eat(); // Calls the parent's eat() method
System.out.println("This dog eats dog food.");
}
}
// In main, you would call it like this:
// Dog myDog = new Dog();
// myDog.eat();