
从 Java 9 开始,我们可以添加私有方法和私有静态 接口中的方法。在接口中使用私有方法的优点是减少默认和静态方法之间的代码重复。例如,如果两个或多个默认方法需要共享某些代码,则可以为其创建一个私有方法,并从每个默认方法中调用。
在 Java 9 中,以下变量/方法已在接口中定义。
- 常量
- 抽象方法 li>
- 默认方法
- 静态方法
- 私有方法
- 私有静态方法
示例
import java.util.*;
import java.util.stream.*;
interface InterfaceTest {
static void printEvenNumbers() {
getDataStream().filter(i -> i%2==0).forEach(System.out::println);
}
static void printLOddNumbers() {
getDataStream().filter(i -> i%2!=0).forEach(System.out::println);
}
private static Stream getDataStream() { // private static method
List list = Arrays.asList(10, 13, 5, 15, 12, 20, 11, 25, 16);
return list.stream();
}
}
public class InterfacePrivateMethodTest implements InterfaceTest {
public static void main(String args[]) {
System.out.println("The even numbers: ");
InterfaceTest.printEvenNumbers();
System.out.println("The odd numbers: ");
InterfaceTest.printLOddNumbers();
}
} 输出
The even numbers: 10 12 20 16 The odd numbers: 13 5 15 11 25










