Sobes.tech
Junior — Middle

Is it possible to implement multiple inheritance in Java?

sobes.tech AI

Answer from AI

In Java, multiple inheritance of classes is not directly supported, meaning a class cannot inherit from multiple classes simultaneously. This is done to avoid issues related to method conflicts and hierarchy complexities.

However, multiple inheritance can be partially achieved through interfaces. A class can implement multiple interfaces, allowing it to inherit behavior from different sources.

Example:

interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Duck implements Flyable, Swimmable {
    public void fly() {
        System.out.println("Duck is flying");
    }
    public void swim() {
        System.out.println("Duck is swimming");
    }
}

Starting from Java 8, interfaces can contain methods with implementations (default methods), which expands the capabilities of multiple inheritance of behavior.