Java Inheritance Essentials
Introduction to Java Inheritance
Sharing Traits Between Classes
In object-oriented programming, we often find that different classes share common characteristics. For instance, a Car and a Bicycle are both types of Vehicle. They both have a speed and can move. Instead of writing the same code for these shared traits in every class, we can use a concept called inheritance.
Inheritance is a mechanism where one class acquires the properties and behaviors of another class. It represents an "is-a" relationship. For example, a
Caris aVehicle.
This parent-child relationship between classes is a cornerstone of Java. The main benefit is code reusability. You write the common code once in a parent class, and child classes can use it without rewriting it. This not only saves time but also makes your code more organized and easier to maintain. When you want to change a common behavior, you only need to update it in one place: the parent class.
How Inheritance Works
To create this parent-child relationship in Java, we use the extends keyword. The class that inherits is called the subclass (or child class), and the class it inherits from is the superclass (or parent class).
superclass
noun
The class whose features are inherited. Also known as a parent or base class.
subclass
noun
The class that inherits from another class. Also known as a child or derived class.
Let's see the syntax in action. Here we have a general Vehicle class.
// This is the superclass
class Vehicle {
String brand = "Generic";
public void honk() {
System.out.println("Beep, beep!");
}
}
Now, let's create a Car class that inherits from Vehicle. By using extends, the Car class automatically gets the brand field and the honk() method from Vehicle.
// This is the subclass
class Car extends Vehicle {
String modelName = "Model T";
}
// Main class to run the code
public class Main {
public static void main(String[] args) {
// Create a Car object
Car myCar = new Car();
// Call the honk() method from the Vehicle class
myCar.honk();
// Access the brand field from the Vehicle class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Even though we never wrote a honk() method or a brand field inside the Car class, our myCar object can use them. That's the power of inheritance. The Car class has its own specific property, modelName, but it also gains all the public features of its parent, Vehicle.
By using extends, you create a clear, logical hierarchy between classes. This makes your code more organized and efficient, forming the foundation for more complex and powerful program structures.