Java 9 在接口中添加了私有方法新功能。可以使用private修饰符来定义私有方法。我们可以在Java 9的接口中添加私有和私有静态方法
接口中私有方法的规则:
interface <interface-name> { private methodName(parameters) { // some statements } }
interface TestInterface { default void methodOne() { System.out.println("This is a Default method One..."); printValues(); // calling a private method } default void methodTwo() { System.out.println("This is a Default method Two..."); printValues(); // calling private method... } private void printValues() { // private method in an interface System.out.println("methodOne() called"); System.out.println("methodTwo() called"); } } public class PrivateMethodInterfaceTest implements TestInterface { public static void main(String[] args) { TestInterface instance = new PrivateMethodInterfaceTest(); instance.methodOne(); instance.methodTwo(); } }
This is a Default method One... methodOne() called methodTwo() called This is a Default method Two... methodOne() called methodTwo() called