Junior — Middle
How can multiple inheritance be emulated in object-oriented languages?.
sobes.tech AI
Answer from AI
In Java, multiple inheritance of classes is not directly supported, but it can be emulated using interfaces and composition.
-
Interfaces — a class can implement multiple interfaces, allowing it to "inherit" behavior from multiple sources.
-
Composition — a class contains objects of other classes and delegates method calls to them, thus combining functionality.
Example with interfaces:
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");
}
}
Example with composition:
class Engine {
void start() { System.out.println("Engine started"); }
}
class Car {
private Engine engine = new Engine();
void start() {
engine.start();
System.out.println("Car is moving");
}
}