Sobes.tech
Middle

Why is multiple inheritance prohibited in some programming languages and how can this restriction be bypassed?

sobes.tech AI

Answer from AI

The restriction was introduced due to the "diamond problem" — ambiguity when calling a method inherited from two parent classes, which in turn inherit from a common ancestor. It is unclear which implementation of the method should be used.

The restriction is bypassed using:

  • Interfaces: A class can implement multiple interfaces, inheriting only one implementation through a class. Interfaces only describe the contract (set of methods), but not their implementation.
  • Composition: An object of a class contains references to objects of other classes and delegates method calls to them. Instead of inheriting behavior, the class uses the behavior of other objects.
// Example of composition
class Engine {
    void start() { /* ... */ }
}

class Car {
    private Engine engine; // Composition

    Car(Engine engine) {
        this.engine = engine;
    }

    void start() {
        engine.start(); // Delegation
    }
}