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

javaobject oriented programmingprogramming更新于 2025/7/15 5:00:17

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

接口中私有方法的规则:

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

语法

interface <interface-name> {
   private methodName(parameters) {
      // 一些语句
   }
}

示例

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

相关文章


有用资源