Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java allow multiple inheritance from interfaces but not from abstract/concrete classes [duplicate]

Possible Duplicate:
Why there is no multiple inheritance in Java, but implementing multiple interfaces is allowed

Why Java allows multiple inheritance from interfaces but not from abstract or concrete classes

like image 313
dan Avatar asked Jun 09 '10 18:06

dan


3 Answers

Multiple inheritance of concrete classes raises a variety of issues.

For example, what if a class inherits two different implementations of the same method from two different base classes?

To avoid these issues, Java doesn't support this feature.
Unlike concrete classes, interfaces cannot have method bodies.

Therefore, none of these issues apply to interfaces.

like image 126
SLaks Avatar answered Oct 12 '22 20:10

SLaks


Because implementing an interface is not inheritance. It simply means that your class will adhere to a predefined contract, typically to provide a set of methods related to a certain functionality. Any class can adhere to many such contracts without conflict (unless two of those interfaces define the same method).

Unlike inheritance, it does not automagically receive attributes or functionality due to a hierarchical relationship with its superclass since no such relationship exists.

Multiple inheritance is basically not allowed in Java or many other OO languages due to the already mentioned Diamond Inheritance problem.

like image 22
Robin Avatar answered Oct 12 '22 20:10

Robin


I really don't like the term "inherit" here, it leads to a lot of confusion.

Java only allows interfaces to extend other interfaces, and for classes to implement interfaces.

If you look at an interface as a mathematical set of declarations, then each "extends" merely provides the union of the set from the superinterface and that of the current interface. You are therefore allowed to do multiple "unions".

When you eventually get to a class that implements one or more interfaces, the semantics here are merely that the class must provide implementations for all the methods in the set. A class implementing multiple interfaces could be rewritten as a class implementing a single interface that extends all the above interfaces.

In the case of classes inheriting multiple classes it is not allowed because it leads to a variety of problems, including the diamond problem. For instance, if I have two supertypes with different implementations of the same method signature, which one should be used in the subtype?

like image 43
Uri Avatar answered Oct 12 '22 20:10

Uri