首頁  >  文章  >  Java  >  在Java 9中,我們可以在介面中定義私有方法或私有靜態方法嗎?

在Java 9中,我們可以在介面中定義私有方法或私有靜態方法嗎?

WBOY
WBOY轉載
2023-09-06 21:29:021202瀏覽

在Java 9中,我们可以在接口中定义私有方法或私有静态方法吗?

是的,我們可以在Java 9 的介面中擁有私有方法私有靜態方法。可以使用這些方法來去除程式碼冗餘。 私有方法只能在該介面中有用或可存取。我們無法從一個介面存取或繼承私有方法到另一個介面或類別。

語法

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

範例

interface Java9Interface {
   public abstract void method1();
   public default void method2() {
      method4();
      method5();
      System.out.println("Inside default method");
   }
   public static void method3() {
      method5();    <strong>//  static method inside other static method</strong>
      System.out.println("Inside static method");
   }
   private void method4() {    <strong>// private method</strong>
      System.out.println("Inside private method");
   }
   private static void method5() {    <strong>// private static method</strong>
      System.out.println("Inside private static method");
   }
}
public class PrivateStaticMethodTest implements Java9Interface {
   @Override
   public void method1() {
       System.out.println("Inside abstract method");
   }
   public static void main(String args[]) {
      Java9Interface instance = new PrivateStaticMethodTest();
      instance.method1();
      instance.method2();
      Java9Interface.method3();
   }
}

輸出

<strong>Inside abstract method
Inside private method
Inside private static method
Inside default method
Inside private static method
Inside static method</strong>

以上是在Java 9中,我們可以在介面中定義私有方法或私有靜態方法嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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