Inheritance in Java: Extending Classes
Introduction to Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit the properties
and behaviors of another class. In Java, inheritance enables code reuse and the creation of hierarchical class
structures.
Base Class and Derived Class
Inheritance involves two types of classes: the base class (or superclass) and the derived class (or subclass). The base class provides the common attributes and behaviors, and the derived class extends or specializes the base class by adding more features.
class Vehicle {
String brand;
int year;
void start() {
System.out.println("Starting the vehicle.");
}
}
class Car extends Vehicle {
int numberOfDoors;
void openTrunk() {
System.out.println("Opening the trunk.");
}
}
Extending a Class
To create a derived class, use the extends
keyword followed by the name of the base class. The derived
class inherits all the non-private attributes and methods of the base class.
class Car extends Vehicle {
int numberOfDoors;
void openTrunk() {
System.out.println("Opening the trunk.");
}
}
Accessing Inherited Members
Inherited members (attributes and methods) can be accessed directly from an object of the derived class.
Car myCar = new Car();
myCar.brand = "Toyota"; // Accessing an inherited attribute
myCar.start(); // Accessing an inherited method
Method Overriding
A derived class can provide its own implementation of a method that it inherits from the base class. This is known
as method overriding.
class Car extends Vehicle {
int numberOfDoors;
@Override
void start() {
System.out.println("Starting the car's engine.");
}
}
Conclusion
Inheritance is a powerful concept in Java that allows you to build complex class hierarchies and promote code reuse.
You've learned about base classes, derived classes, method overriding, and how to extend classes in this guide. As
you continue to develop Java applications, inheritance will be a key tool for structuring and organizing your code.