参考答案:
Java 8 对接口进行了重大升级,新增了一些特性,增强了接口的功能,使得接口更加灵活和强大。以下是 Java 8 接口新增的主要特性:
default
关键字修饰。1interface MyInterface { 2 default void defaultMethod() { 3 System.out.println("This is a default method."); 4 } 5} 6 7class MyClass implements MyInterface { 8 // 可以选择不重写默认方法 9} 10 11public class Main { 12 public static void main(String[] args) { 13 MyClass obj = new MyClass(); 14 obj.defaultMethod(); // 输出: This is a default method. 15 } 16}
static
关键字修饰。1interface MyInterface { 2 static void staticMethod() { 3 System.out.println("This is a static method."); 4 } 5} 6 7public class Main { 8 public static void main(String[] args) { 9 MyInterface.staticMethod(); // 输出: This is a static method. 10 } 11}
private
关键字修饰。1interface MyInterface { 2 default void defaultMethod1() { 3 helperMethod(); 4 } 5 6 default void defaultMethod2() { 7 helperMethod(); 8 } 9 10 private void helperMethod() { 11 System.out.println("This is a private method."); 12 } 13} 14 15public class Main { 16 public static void main(String[] args) { 17 MyInterface obj = new MyInterface() {}; // 匿名实现 18 obj.defaultMethod1(); // 输出: This is a private method. 19 obj.defaultMethod2(); // 输出: This is a private method. 20 } 21}
最近更新时间:2024-12-09