Java is an object-oriented programming language, and with this comes the concept of inheritance. Inheritance allows us to define a class that inherits all the members (fields and methods) from another class. To access the members of a superclass (parent class) from a subclass (child class), Java provides us with a special keyword called super
.
To understand further, we must clarify that the primary purpose of the 'super' keyword in Java is to call a method of the parent class.
When a behavior (method) in the parent class is necessary for the child class, we use 'super' to call that method. This allows the child class to reuse the code present in the parent class, promoting efficient programming principle of DRY (Don't Repeat Yourself).
Here is an example to demonstrate its usage.
class Vehicle {
void start() {
System.out.println("Starting the vehicle...");
}
}
class Car extends Vehicle {
void start() {
super.start(); // calling the start method of parent class.
System.out.println("Starting the car...");
}
}
public class Main {
public static void main(String args[]) {
Car myCar = new Car();
myCar.start();
}
}
When you run this code, it will first call the start()
method of Vehicle
class (due to super.start()
) and then its own start()
method. The output would be:
Starting the vehicle...
Starting the car...
While it's essential to understand the correct use of the super
keyword, it's equally important to know the best practices around it.
Remember, using 'super' correctly can greatly improve code reusability and understandability, making maintenance easier and error-free. Its ability to establish a clear relationship between the parent and child class is pivotal in maintaining the object-oriented architecture of your Java code.