Welcome to our deep dive into the fascinating world of Java! Today, we'll explore the super keyword, a powerful tool in the Java programming language.
super keyword? 📝The super keyword in Java is a reference to the immediate parent class. It allows us to call methods, constructors, and access variables from the parent class within the subclass.
super keyword? 💡In object-oriented programming, a child class (also known as a subclass) inherits properties and methods from its parent class. The super keyword comes in handy when we need to access those inherited elements explicitly.
super keyword with examples 🎯Let's consider a simple example where we have a Vehicle class and a Car class that inherits from Vehicle. The Vehicle class has a method called startEngine().
// Vehicle class
public class Vehicle {
public void startEngine() {
System.out.println("Engine started.");
}
}
// Car class
public class Car extends Vehicle {
public void specificStartupSound() {
System.out.println("Brrrmm, Engine started.");
}
}Now, in the Car class, we want to call the startEngine() method from the Vehicle class. We can do this using the super keyword:
public class Car extends Vehicle {
public void specificStartupSound() {
super.startEngine(); // Calling the startEngine() method from Vehicle
System.out.println("Brrrmm, Engine started.");
}
}When you run the code, you will see the following output:
Engine started.
Brrrmm, Engine started.
Sometimes, we might want to call the parent class constructor from the subclass constructor. We can achieve this using the super() keyword:
// Parent class
public class Vehicle {
private String color;
public Vehicle(String color) {
this.color = color;
System.out.println("Created a new vehicle of color: " + color);
}
}
// Child class
public class Car extends Vehicle {
private int numberOfDoors;
public Car(String color, int numberOfDoors) {
super(color); // Calling the Vehicle constructor
this.numberOfDoors = numberOfDoors;
System.out.println("Created a new car with " + numberOfDoors + " doors.");
}
}When you run the code, you will see the following output:
Created a new vehicle of color: Red
Created a new car with 4 doors.
What does the `super` keyword refer to in Java?
With this, we've explored the super keyword in Java and learned how to use it to call methods, constructors, and access variables from the parent class within the subclass. Happy coding! 🚀