Java 9 中接口的私有方法规则是什么?


Java 9 添加了私有方法接口的新特性。私有方法可以使用private修饰符定义。从Java 9开始,我们可以在接口中添加privateprivate static方法

接口中私有方法的规则

  • 接口中私有方法有方法体,这意味着它不能像通常在接口中那样声明为普通的抽象方法。如果尝试声明没有方法体的私有方法,则会抛出错误:“此方法需要方法体而不是分号”。
  • 我们不能在接口中同时使用privateabstract修饰符。
  • 如果要从接口中的静态方法访问私有方法,则该方法可以声明为private static 方法,因为我们不能对非静态方法进行静态引用。
  • 非静态上下文中使用private static 方法,意味着它可以从接口中的默认方法调用。

语法

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();
   }
}

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

This is a Default method One...
methodOne() called
methodTwo() called
This is a Default method Two...
methodOne() called
methodTwo() called

更新于:2020年2月21日

822 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告