default方法特性
在Java中,接口中的default方法是一种特殊的成员方法,具有以下特性:
- default方法可以有方法体
- 接口中的普通方法必须被实现类重写;默认方法可以不被实现类重写。
- 默认方法可以通过接口的实现对象直接调用,也可以被接口的实现类重写
- 如果一个实现类只实现了一个接口,那么可以不用重写接口中的默认方法
- 如果一个实现类同时实现了多个接口,并且在这些接口中存在同名的默认方法,则实现类必须至少重写其中一个同名方法。
此外,默认方法的引入是为了解决在接口扩展时可能遇到的维护问题。
在接口中新增方法时,如果新增的这个方法写成普通方法的话,那么需要在该接口所有的实现类中都重写这个方法。如果新增的方法定义为default类型,就不需要在所有的实现类中全部重写该default方法,哪个实现类需要新增该方法,就在哪个实现类中进行实现。
通过允许接口提供默认实现,而不是强迫所有实现类都必须覆盖它们,可以减少对现有实现的影响,并确保向后兼容性(即向前兼容)。
例如,Iterable接口的foreach
方法就是一个默认方法,它提供了遍历元素的标准操作,而不必要求每个实现类都自行编写这样的方法。
总结来说,接口中的默认方法是设计用来简化接口扩展和增强灵活性的机制
同时实现多个接口
public interface Interface1{
default void helloWorld() {
System.out.println("hi i'm from Interface1");
}
}
public interface Interface2{
default void helloWorld() {
System.out.println("hi i'm from Interface2");
}
}
/**
实现接口Interface1,Interface2
*/
public class MyImplement implements Interface1,Interface2{
public static void main(String[] args) {
MyImplement myImplement = new MyImplement();
//直接调用helloWorld()方法
myImplement.helloWorld();
}
}
如果一个实现类同时实现了多个接口,并且在这些接口中存在同名的默认方法,不实现这些默认方法会怎样呢?
答案肯定无疑:编译器在检查的时候路就会出现报错。
答案肯定无疑:编译器在检查的时候路就会出现报错。
具体如何解决这个问题呢?
当然就是在最新的实现类上重写这个default方法
/**
实现接口Interface1,Interface2
*/
public class MyImplement implements Interface1,Interface2{
public static void main(String[] args) {
MyImplement myImplement = new MyImplement();
//直接调用helloWorld()方法
myImplement.helloWorld();
}
@Override
public void helloWorld() {
// 直接调用父类的接口中的默认方法!!!
// Interface1.super.helloWorld();
System.out.println("hi i'm from MyImplement");
}
}
类优先于接口
当实现类同时继承了其他类,并且实现了接口,而其他类的方法和接口的默认方法都存在的时候 ,会优先执行被继承的类的方法。
public class MyImplement2 extends MyImplement implements Interface2{
public static void main(String[] args) {
MyImplement2 myImplement2 = new MyImplement2();
myImplement2.helloWorld();
}
}
参考文献
https://blog.csdn.net/t194978/article/details/132558922
54a71d3295d7b.png#pic_center)
参考文献
https://blog.csdn.net/t194978/article/details/132558922
https://blog.csdn.net/qq_45488981/article/details/131751566