Video in progress

Why can't a class in Java inherit from two classes at the same time?

Because of the "diamond problem": if two parent classes have the same method or field, it is ambiguous which one is inherited. Java forbids multiple inheritance for classes to keep the language simple, but a class can implement several interfaces.

📖 Answer

Imagine both Printer and Scanner have a start(). If class Mfu extends Printer, Scanner were allowed, which code would new Mfu().start() run? On top of that, the fields of both parents could end up in the child object twice. In C++ there is a separate virtual inheritance mechanism for this.

Java's solution:

  • for classes, only one extends;
  • for interfaces, as many implements as you like.
class Mfu implements Printable, Scannable { ... }

Interfaces have had default methods since Java 8, so a conflict can happen there too. But in that case the compiler forces you to resolve it: you override the conflicting method in the class yourself. And the fact that interfaces have no state (instance fields) makes the problem much easier.

If you need the behavior of several classes, you usually use composition: Mfu holds Printer and Scanner objects as fields.