七、接口中的默认方法与静态方法
1.接口的默认方法
Java 8中允许接口中包含具有具体实现的方法,该方法称为“默认方法”,默认方法使用 default 关键字修饰。
package com.zsr.interfacemethod;
public interface MyInterface1{
default String fun1(){
return "接口MyInterface1中的默认方法fun1~";
}
}
接口默认方法的 ” 类优先 ” 原则
若一个接口中定义了一个默认方法,而另外一个父类或接口中又定义了一个同名的方法时
- 选择父类中的方法。如果一个父类提供了具体的实现,那么接口中具有相同名称和参数的默认方法会被忽略。
public class Father {
public String fun1(){
return "父类Father中的方法fun1~";
}
}
class Test1 extends Father implements MyInterface1{
public static void main(String[] args){
String s = new Test1().fun1();
System.out.println(s);
}
}
结果:

- 接口冲突。如果一个父接口提供一个默认方法,而另一个接口也提供了一个具有相同名称和参数列表的方法(不管方法是否是默认方法),那么必须覆盖该方法来解决冲突
public interface MyInterface2 {
default String fun1(){
return "父接口MyInterface2中的默认方法fun1~";
}
}
class Test2 implements MyInterface1,MyInterface2{
public static void main(String[] args){
String s = new Test2().fun1();
System.out.println(s);
}
@Override
public String fun1() {
return MyInterface2.super.fun1();
}
}
结果:

2.接口中的静态方法
Java8 中,接口中允许添加静态方法。
public interface MyInterface3 {
static String show(){
return "静态方法show()";
}
}
class Test3 implements MyInterface3{
public static void main(String[] args){
String s = MyInterface3.show();
System.out.println(s);
}
}
结果:

注:菜鸟一枚,才疏学浅,希望各位前辈能够批评指正,感谢感谢!!!
本文详细介绍了Java8中接口的默认方法和静态方法的使用。默认方法允许接口拥有具体实现,通过default关键字声明。当接口方法与类方法同名时,遵循类优先原则。静态方法则直接在接口中声明为static,无需实例化即可调用。文章通过示例代码展示了这些概念的实际应用。
——接口中的默认方法与静态方法&spm=1001.2101.3001.5002&articleId=102951758&d=1&t=3&u=24401cd0fc694f2c971bfb8838839709)
9476

被折叠的 条评论
为什么被折叠?



