Saturday, June 26, 2010

Chapter 2: Deadly Diamond of Death (Multiple inheritance)

there is a question I used to hear a lot especially in the interviews: Why Java doesn't support multi-inheritance?

And the answer for this question is that multi-inheritance have some issues the compiler needs to deal with. One of them is Deadly Diamond of Death. If u look to the following diagram.

7c47d9f8-b09c-4cdf-8568-ee7bb689100d

There is two problems in this situation:


1- class D inherit function f implementation 2 times. So which implementation of function f does inherit? In C++ u have to override this function to solve this problem.

2- Class A have member variable i since B & C inherit from A so there's ambiguity. we may want this variable to be separated that means creating two copies of A in D or if we want one copy so we have to to use the virtual inheritance.

==> that's two reasons was enough for java designers to avoid the multi-inheritance in their design.

extracted from what I understand from: http://www.objectmentor.com/resources/articles/javacpp.pdf