Java 8的菱形继承冲突解决之道

关于Java8的菱形继承(又名:钻石结构)

我之前有写过关于Python的菱形继承,在Java 8中,java的官方对于菱形继承,有独特的解决办法,即显性调用。

例子

public interface A {
   default void hello(){
       System.out.println("This is A hello");
    }  
}
public interface B extends A{
   default void hello(){
       System.out.println("This is B hello");
    } 
}

public class C implements A,B {
   public static void main(String[] args) {
        new C().hello();
    }
}

输出&结论

因为B比A更具体,所以应该选择B的hello方法。
所以,程序会打印输出“This is B hello”
解决冲突,显式调用
Java 8中引入了一种新的语法X.super.m(…),
其中X是你希望调用的m方法所在的父接口。
假如你希望C使用来自于B的默认方法,调用方式如下所示:

public interface A {
   default void hello(){
       System.out.println("This is A hello");
    }  
}
public interface B{
   default void hello(){
       System.out.println("This is B hello");
    } 
}

public class C implements A,B {
   public void hello() {
        B.super.hello();
    }
}

结论:1、越具体优先级越高,2、Java类或父类中显式声明的方法,其优先级高于所有的默认方法,3、两个默认方法都同样具体时,你需要在类中覆盖该方法,显式地选择使用哪个接口中提供的默认方法。

你可能感兴趣的:(java,java,开发语言)