首頁  >  文章  >  Java  >  在Java 9中,介面中的私有方法有哪些規則?

在Java 9中,介面中的私有方法有哪些規則?

WBOY
WBOY轉載
2023-08-31 12:57:111268瀏覽

在Java 9中,接口中的私有方法有哪些规则?

Java 9 在介面中新增了私有##方法新功能。可以使用private修飾符來定義私有方法。我們可以在Java 9的介面中加入私有私有#靜態方法

介面中私有方法的規則:

    私有方法的主體位於介面意味著我們不能像通常在介面中那樣宣告為普通的抽象方法。如果我們試圖宣告一個沒有主體的私有方法,那麼它可能會拋出一個錯誤,指出「
  • 此方法需要主體而不是分號」。
  • 我們不能同時在介面中使用
  • 私有抽象修飾符。
  • 如果我們想要從介面中的靜態方法存取私有方法,那麼方法可以宣告為
  • 私有靜態方法,因為我們無法對非靜態方法進行靜態引用。
  • A
  • 非靜態上下文中使用的私有靜態方法意味著它可以從介面中的預設方法呼叫。
語法

<strong>interface <interface-name> {
   private methodName(parameters) {
      // some statements
   }
}</strong>

範例

interface TestInterface {
   <strong>default </strong>void methodOne() {
      System.out.println("This is a Default method One...");
      printValues(); // calling a private method
   }
   <strong>default </strong>void methodTwo() {
      System.out.println("This is a Default method Two...");
      printValues(); // calling private method...
   }
   <strong>private </strong>void <strong>printValues</strong><strong>()</strong> { <strong>// private method in an interface
</strong>      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();
   }
}

輸出

<strong>This is a Default method One...
methodOne() called
methodTwo() called
This is a Default method Two...
methodOne() called
methodTwo() called</strong>

以上是在Java 9中,介面中的私有方法有哪些規則?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除