Multiple Inheritance with Interfaces

Java does not support multiple inheritance with classes, but it allows a class to implement multiple interfaces. This enables a form of multiple inheritance and provides a way to achieve more modular and flexible designs.

interface Engine {
    void startEngine();
}

interface Wheels {
    void rotateWheels();
}

class Truck implements Engine, Wheels {
    @Override
    public void startEngine() {
        System.out.println("Truck engine is starting.");
    }

    @Override
    public void rotateWheels() {
        System.out.println("Truck wheels are rotating.");
    }

    public static void main(String[] args) {
        Truck myTruck = new Truck();
        myTruck.startEngine(); // Output: Truck engine is starting.
        myTruck.rotateWheels(); // Output: Truck wheels are rotating.
    }
}

In this example:

  • The Truck class implements both Engine and Wheels interfaces, allowing it to inherit behaviors from both.

Interface Inheritance

Interfaces can extend other interfaces, similar to how classes extend other classes. This allows for more complex interfaces to be built upon simpler ones.

// Base interface
interface Animal {
    void eat();
}

// Derived interface that extends Animal
interface Mammal extends Animal {
    void walk();
}

class Dog implements Mammal {
    @Override
    public void eat() {
        System.out.println("Dog is eating.");
    }

    @Override
    public void walk() {
        System.out.println("Dog is walking.");
    }

    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat();  // Output: Dog is eating.
        myDog.walk(); // Output: Dog is walking.
    }
}

In this example:

  • The Mammal interface extends the Animal interface, inheriting the eat() method.
  • The Dog class implements the Mammal interface, providing implementations for both eat() and walk() methods.