ToB企服应用市场:ToB评测及商务社交产业平台
标题:
JDK7 JDK8 JDK9接口中的默认方法、静态方法、私有方法
[打印本页]
作者:
不到断气不罢休
时间:
2024-6-15 01:59
标题:
JDK7 JDK8 JDK9接口中的默认方法、静态方法、私有方法
JDK8开始之后接口新增的方法
JDK7从前:接口中只能定义抽象方法
JDK8的新特性:接口中可以定义有方法体的方法(默认、静态)
JDK9的新特性:接口中可以定义私有方法
<strong> 接口中的默认方法
</strong>
InterA
复制代码
package com.itheima.a06;
public interface InterA {
// 抽象方法 不能拥有方法体
public abstract void show();
// public 可以省略 default不可以省略
public default void print() {
System.out.println("A接口中的默认方法---print");
}
}
复制代码
InterB
复制代码
package com.itheima.a06;
public interface InterB {
// 抽象方法 不能拥有方法体
public abstract void show();
// public 可以省略 default不可以省略
public default void print() {
System.out.println("B接口中的默认方法---print");
}
}
复制代码
intermpl
复制代码
package com.itheima.a06;
public class intermpl implements InterA,InterB {
@Override
public void show() {
System.out.println("实现类 重写的抽象方法");
}
// 默认方法不是抽象方法 不强制重写 如果重写 去掉default关键字
// 实现多个接口 多个接口存在相同名字的默认方法,子类就必须对该方法重写
@Override
public void print() {
System.out.println("重写接口中的默认方法");
}
}
复制代码
Test
复制代码
package com.itheima.a06;
public class Test {
public static void main(String[] args) {
intermpl ii=new intermpl();
ii.show();
ii.print();
}
}
复制代码
JDK8以后新增的静态方法
Inter
复制代码
package com.itheima.a07;
public interface Inter {
public abstract void method();
// 静态方法不能被重写
public static void show(){
System.out.println("Inter方法中的静态方法");
};
}
复制代码
InterImpl
复制代码
package com.itheima.a07;
public class InterImpl implements Inter {
@Override
public void method() {
System.out.println("InterImpl中重写的抽象方法");
}
// 不叫重写
public static void show(){
System.out.println("InterImpl方法中的静态方法");
};
}
复制代码
Test
复制代码
package com.itheima.a07;
public class Test {
public static void main(String[] args) {
// 调用接口中的静态方法
Inter.show();
// 调用实现类中的静态方法
InterImpl.show();
}
}
复制代码
JDK9以后的私有方法
InterA
复制代码
package com.itheima.a08;
public interface InterA {
public default void show1(){
System.out.println("show1方法执行");
show3();
};
public default void show2(){
System.out.println("show2方法执行");
show3();
};
//普通私有方法,给默认方法服务
private void show3(){
System.out.println("记录细节的代码");
};
public static void show11(){
System.out.println("show1方法执行");
show4();
};
public static void show22(){
System.out.println("show2方法执行");
show4();
};
//静态私有方法,给静态方法服务
private static void show4(){
System.out.println("记录细节的代码");
};
}
复制代码
总结
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4