加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:21:12 所属栏目:Java 来源:网络整理
导读:参见英文答案 Why is Multiple Inheritance not allowed in Java or C#?????????????????????????????????????17个 ???????????? Why is there no multiple inheritance in Java,but implementing multiple interfaces is allowed??????????????????????????
参见英文答案 > Why is Multiple Inheritance not allowed in Java or C#?????????????????????????????????????17个
>???????????? Why is there no multiple inheritance in Java,but implementing multiple interfaces is allowed?????????????????????????????????????16个
在C中,你可以扩展许多类,那么这个设计在Java中的优势是什么类只能扩展一个类?
由于接口是一种纯类(实际上是抽象类),为什么不像类扩展一样限制接口的实现数量呢?

解决方法

能够只扩展一个基类是解决 diamond problem的一种方法.这是一个问题,当一个类扩展了两个实现相同方法的基类时 – 你怎么知道要调用哪一个?

A.java:

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

B.java:

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

C.java:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读