Sobes.tech
Junior — Middle

How can you implement functionality similar to multiple inheritance in object-oriented languages?

sobes.tech AI

Answer from AI

In languages like Java, which do not support multiple inheritance of classes directly, similar functionality can be implemented using interfaces and composition.

  1. Interfaces:

    • A class can implement multiple interfaces, allowing it to inherit contracts from different sources.
    • Since Java 8, interfaces can contain methods with implementations (default methods), bringing them closer to partial implementation.
  2. Composition:

    • Instead of inheritance, a class contains references to objects of other classes and delegates method calls to them.
    • This allows combining behaviors of different classes without inheritance.

Example of using interfaces and composition:

interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Bird implements Flyable {
    public void fly() {
        System.out.println("Bird is flying");
    }
}

class Fish implements Swimmable {
    public void swim() {
        System.out.println("Fish is swimming");
    }
}

class Duck implements Flyable, Swimmable {
    private Bird bird = new Bird();
    private Fish fish = new Fish();

    public void fly() {
        bird.fly();
    }

    public void swim() {
        fish.swim();
    }
}

Thus, the Duck class combines flying and swimming behaviors, implementing functionality similar to multiple inheritance.

How can you implement functionality similar to… - sobes.tech