菱形继承问题(default)

来源:互联网 发布:keynote 模板 知乎 编辑:程序博客网 时间:2024/04/26 06:14

菱形继承问题(default)

//InterfaceApublic interface InterfaceA {    default void hello(){        System.out.println("hello from A");    }}//InterfaceApublic interface InterfaceB extends InterfaceA{}//InterfaceApublic interface InterfaceC extends InterfaceA {}//ClassDpublic class ClassD implements InterfaceB, InterfaceC {    public static void main(String[] args){        new ClassD().hello();    }}//consolehello from A....

但是如果在InterfaceB和InterfaceC中重写hello的方法,那么在ClassD中必须重写hello方法,不然编译会报错,可以指定继承其中一个接口中的方法:

public interface InterfaceA {    default void hello(){        System.out.println("hello from A");    }}//public interface InterfaceB extends InterfaceA{    @Override    default void hello() {        System.out.println("hello from B");    }}//public interface InterfaceC extends InterfaceA {    @Override    default void hello() {        System.out.println("hello from C");    }}public class ClassD implements InterfaceB, InterfaceC {    public static void main(String[] args){        new ClassD().hello();    }    @Override    public void hello() {        InterfaceB.super.hello();    }}//consolehello from B...

遵守下面这三条准则就能解决所有可能的冲突:

  • 首先,类或父类中显式声明的方法,其优先级高于所有的默认方法。
  • 如果用第一条无法判断,方法签名又没有区别,那么选择提供最具体实现的默认方法的接口。
  • 最后,如果冲突依旧无法解决,你就只能在你的类中覆盖该默认方法,显式地指定在你的类中使用哪一个接口中的方法。
原创粉丝点击