Java Inheritance: Understanding Class Hierarchies
Learn about Java inheritance, a fundamental concept in object-oriented programming that enables a class to inherit attributes and methods from another class. This guide covers the key principles of inheritance, including class hierarchies and the benefits of code reusability.
Java Inheritance
Inheritance allows one class to inherit attributes and methods from another class. It involves:
- Subclass (child): the class that inherits
- Superclass (parent): the class being inherited from
Use the extends
keyword to inherit from a class.
Example
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
Car myCar = new Car(); // Create a myCar object
myCar.honk(); // Call the honk() method (from Vehicle)
System.out.println(myCar.brand + " " + myCar.modelName); // Display brand and modelName
}
}
Output
Tuut, tuut!
Ford Mustang
The protected
modifier allows access within the same package and subclasses. If set to private
, it wouldn't be accessible by the subclass.
Why Use Inheritance?
- Code reusability: reuse attributes and methods of an existing class when creating a new class.
For more advanced concepts, check the next chapter on Polymorphism.
The final Keyword
To prevent a class from being inherited, use the final
keyword:
Example
final class Vehicle {
// class definition
}
class Car extends Vehicle { // Error: cannot inherit from final Vehicle
// class definition
}
Output
Main.java:9: error: cannot inherit from final Vehicle
class Main extends Vehicle {
^
1 error