Why do some languages restrict multiple inheritance, and what is the diamond problem?
Because inheriting from two classes that both have state gives you two copies of the state, and there is no way for the language to say which one you meant. So the languages that allow it either have very strict rules or have found that the problems are worse than the benefit.
public class Main {
public static void main(String[] args) {
Printable p = new LaserPrinter();
System.out.println(p.describe());
}
}
And here are the two sides that would be combined.
public interface Printable {
String describe();
}
public interface Scannable {
byte[] scan();
}
So what is the diamond problem? It is this. You have a class at the top, two classes below it, and a class at the bottom that inherits from both of them. And the bottom class gets the top class twice, once through each path. So if the top class has state, the bottom class has two separate copies of it, and they can get out of step.
Top
/ \
Left Right
\ /
Bottom
And here is the problem in plain words. If Top has a counter that starts at zero, and Left and Right both inherit it, and Bottom inherits both of them, then Bottom has two counters. So when you increase one of them, the other one does not change, and the object has two different answers to the question of what its counter is.
And there is a second problem with the diamond, and it is about the methods. If Top has a method and both Left and Right override it, then Bottom has two versions of that method and the language has to say which one it runs.
the problem what goes wrong
------------------------- --------------------------------------------
the state is copied twice the two copies get out of step
the method is ambiguous the language has to pick one and you
cannot say which
the change is hard fixing it means changing the top
class, which everybody uses
And Java solves this by not allowing multiple inheritance of classes. So you can only have one parent class, and the state comes from one place.
So the rule to remember is this. One parent class means one copy of the state, and that is why Java allows only one.
The next two questions in this topic are about how Java combines behaviour and about the modern solutions.