开发者

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

开发者 https://www.devze.com 2023-01-02 17:29 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Why there is no multiple inheritanc开发者_如何学编程e in Java, but implementing multiple interfaces is allowe
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Why there is no multiple inheritanc开发者_如何学编程e in Java, but implementing multiple interfaces is allowed

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


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.


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.


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?


To make language simpler and more elegant. C++ allows a lots of stuff, but it's often pain to learn and use. We (me, at least :)) don't want java to be like that.

0

精彩评论

暂无评论...
验证码 换一张
取 消