当前位置:首页 > 编程笔记 > 正文
已解决

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

来自网友在路上 175875提问 提问时间:2023-10-23 20:14:42阅读次数: 75

最佳答案 问答题库758位专家为你答疑解惑

关于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、两个默认方法都同样具体时,你需要在类中覆盖该方法,显式地选择使用哪个接口中提供的默认方法。

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Java 8的菱形继承冲突解决之道":http://eshow365.cn/6-22677-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!