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

輸出

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

更新於:2020年2月21日

822 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.