Java Inheritance

Java Inheritance is a fundamental concept in object-oriented programming (OOP) that allows classes to inherit properties and behaviors from other classes. Inheritance establishes a hierarchical relationship between classes, where a subclass (also known as a derived class) inherits the members of a superclass (also known as a base class). This mechanism promotes code reusability and facilitates the creation of more specialized classes based on existing ones.

In Java, inheritance is achieved through the extends keyword. The subclass inherits all non-private fields and methods from its superclass. It can also define additional fields and methods specific to its own requirements. The superclass serves as a blueprint for the subclass, providing a foundation for its functionality.

Example

Here’s an example to illustrate Java Inheritance:

// The superclass
class Vehicle {
    private String brand;

    public Vehicle(String brand) {
        this.brand = brand;
    }

    public void startEngine() {
        System.out.println("Starting the engine of " + brand);
    }

    public void stopEngine() {
        System.out.println("Stopping the engine of " + brand);
    }
}

// The subclass
class Car extends Vehicle {
    private int numOfDoors;

    public Car(String brand, int numOfDoors) {
        super(brand); // Calling the superclass constructor
        this.numOfDoors = numOfDoors;
    }

    public void openDoors() {
        System.out.println("Opening " + numOfDoors + " doors");
    }
}

// Using the classes
public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 4);
        myCar.startEngine(); // Inherited from Vehicle class
        myCar.openDoors();   // Defined in Car class
        myCar.stopEngine();  // Inherited from Vehicle class
    }
}

In this example, we have a Vehicle superclass that has a brand field and two methods: startEngine() and stopEngine(). The Car class extends Vehicle using the extends keyword. It adds an additional field numOfDoors and a method openDoors().

In the Main class, we create an instance of Car called myCar. We can see that myCar inherits the startEngine() and stopEngine() methods from the Vehicle class. Additionally, it can use the openDoors() method specific to the Car class.

Java Inheritance allows us to reuse the existing functionality of the superclass and extend it further in subclasses, promoting modularity and code organization. It forms the basis for many advanced concepts like polymorphism and abstraction in Java.