为什么Java类只能扩展一个类却实现了很多接口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18863374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:43:11  来源:igfitidea点击:

why Java class can extends only one class but implements many interfaces?

javamultiple-inheritance

提问by Bin

In C++, you can extends many classes, so what's the advantages of this design in Java that a class can only extends one class ? Since interface is a pure kind of class(abstract class actually), why not limit the number of interfaces implementation just like class extension ?

在C++中可以扩展很多类,那么Java中一个类只能扩展一个类有什么好处呢?既然接口是一种纯类(实际上是抽象类),为什么不像类扩展那样限制接口实现的数量呢?

采纳答案by Chris Hayes

Being able to extend only one base class is one way of solving the diamond problem. This is a problem which occurs when a class extends two base classes which both implement the same method - how do you know which one to call?

只能扩展一个基类是解决菱形问题的一种方法。这是一个问题,当一个类扩展两个实现相同方法的基类时会出现这个问题——你怎么知道要调用哪个?

A.java:

A.java:

public class A {
    public int getValue() { return 0; }
}

B.java:

B.java:

public class B {
    public int getValue() { return 1; }
}

C.java:

C.java:

public class C extends A, B {
    public int doStuff() { 
        return super.getValue(); // Which superclass method is called?
    }
}

Since interfaces cannot have implementations, this same problem does not arise. If two interfaces contain methods that have identical signatures, then there is effectively only one method and there still is no conflict.

由于接口不能有实现,所以不会出现同样的问题。如果两个接口包含具有相同签名的方法,那么实际上只有一种方法并且仍然没有冲突。