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

编程入门 行业动态 更新时间:2024-10-20 16:41:50

Java 8的<a href=https://www.elefans.com/category/jswz/34/1762695.html style=菱形继承冲突解决之道"/>

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 8的菱形继承冲突解决之道

本文发布于:2023-12-04 12:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1660872.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:菱形   解决之道   冲突   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!