Understanding Java Inheritance
In Java, inheritance is a mechanism that allows a class (subclass or derived class) to inherit properties and behaviors from another class (superclass or base class). This promotes code reuse and the creation of a hierarchical structure.
Types of Inheritance:
- Single Inheritance:
- Multiple Inheritance:
- Multilevel Inheritance:
- Hierarchical Inheritance:
Single inheritance involves a subclass inheriting from only one superclass. In Java, a class can extend only one class at a time.
Multiple inheritance involves a subclass inheriting from more than one superclass. Java does not support multiple inheritance for classes to avoid the diamond problem. However, it supports multiple inheritance through interfaces.
Multilevel inheritance involves a chain of inheritance with more than two levels. A subclass inherits from another class, and then another class inherits from that subclass, forming a chain.
Hierarchical inheritance involves multiple subclasses inheriting from a single superclass. Each subclass can add its features while sharing common features from the same superclass.
Defining a Superclass:
// Define a superclass named 'Vehicle'
public class Vehicle {
// Fields
String brand;
int year;
// Constructor
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}
// Method
public void startEngine() {
System.out.println("Engine started");
}
}
Creating a Subclass:
// Define a subclass named 'Car' that extends 'Vehicle'
public class Car extends Vehicle {
// Additional fields
int numberOfDoors;
// Constructor
public Car(String brand, int year, int numberOfDoors) {
// Call the superclass constructor
super(brand, year);
// Initialize subclass-specific fields
this.numberOfDoors = numberOfDoors;
}
// Override method from the superclass
@Override
public void startEngine() {
System.out.println("Car engine started");
}
// Additional method
public void drive() {
System.out.println("Car is moving");
}
}
Example:
// Create an object of the 'Car' subclass
Car myCar = new Car("Toyota", 2022, 4);
// Access fields from the superclass
System.out.println("Brand: " + myCar.brand);
System.out.println("Year: " + myCar.year);
// Access fields from the subclass
System.out.println("Number of doors: " + myCar.numberOfDoors);
// Invoke methods from the superclass and subclass
myCar.startEngine();
myCar.drive();
Note:
Inheritance in Java promotes the reuse of code and allows for the creation of a class hierarchy. Subclasses inherit the properties and methods of the superclass, enabling you to model relationships between classes in a more organized way.