views:

738

answers:

4

Java is not allowing inheritance from multiple classes (still it allows inheritance from multiple interfaces.), I know it is very much inline with classic diamond problem. But my questions is why java is not allowing multiple inheritance like C++ when there is no ambiguity (and hence no chances of diamond problem) while inheriting from multiple base class ?

+10  A: 

It was a design decision of Java. You'll never get it, so don't worry too much about it. Although MI might help you make Mixins, that's the only good MI will ever do you.

Randolpho
+5  A: 

I have read that most programmers don't use multiple inheritance in a proper way. "Just go ahead and inherit from a class just to reuse code" is not the best practice in case of multiple inheritance.

Many programmers do not know when to use simple inheritance in most cases. Multiple inheritance must be used with caution and only if you know what you are doing if you want to have a good design.

I don't think that the lack of multiple inheritance in java (as in c++) will put restrictions in your code / application design / problem domain mapping into classes.

andreas
A: 

One simple answer is that all classes in Java derive from java.lang.Object IIRC. So, you would always have a diamond problem... :-D

Massa
Not really. Parent->Child->Object. So Parent extends Child, Child extends Object, it just isn't written explicitly in the latter case, as it is implied automatically.
Adam Batkin
@Massa: Diamond problem occurs when there are multiple implementation in multiple base class (from which child class is derived from) of same method. If we are not overriding methods defined in java.lang.Object class then essentially it doesn't leads to ambiguity and diamond problem.
Silent Warrior
"If we are not overriding methods defined in java.lang.Object" I override toString, hashcode and equals much more often than I want multiple inheritance
Pavel Feldman
@Silent_Warrior: and no, just the fact that you can be calling a method on either one of the grandparent's embedded instance is enough to create a problem with the diamond problem. Suppose you Have Base -> D1, Base -> D2, DD -> D1 and D2. Now suppose Base has an integer attribute called "state". And that you have a method m1 that in D1's version, increments state BUT in D2's version increments state TWICE. In a DD variable, what is the value of the state attribute after calling such method a bunch of times? -- this example aligns well with toString, hashcode and equals, like @Pavel said above
Massa