jdk9中接口开始支持私有方法,主要目的是提升interface的灵活性,方便实现多继承等特性。写段代码展示一下:
/*** 测试接口*/public interface MyInterface {//jdk7: 只能声明全局常量 (public static final)和抽象方法 (public abstract)String STR = "常量";void method1();//jdk8: 可以生命静态方法(public static) 和默认方法static void method2() {System.out.println("静态方法体 method2");}default void method3() {System.out.println("默认实现 method3");}//jdk9:可以声明私有方法(private)private void method4() {System.out.println("私有方法 method4");}}
/*** 测试一下 MyInterface* @see MyInterface*/public class MyTest {public static void main(String[] args) {// MyInterface myi = new MyInterface() {// @Override// public void method1() {// System.out.println("抽象方法1");// }// };//以上写法,简化为Lambda表达式MyInterface myi = () -> System.out.println("抽象方法 method1");myi.method1(); //抽象方法调用MyInterface.method2();//静态方法调用myi.method3();//默认方法调用// myi.method4();//'method4()' has private access in 'MyInterface' 私有方法调用报错//--输入如下:--//抽象方法 method1//静态方法体 method2//默认实现 method3}}
