首頁 >Java >java教程 >在Java 9中,我們可以在介面中使用私有方法嗎?

在Java 9中,我們可以在介面中使用私有方法嗎?

WBOY
WBOY轉載
2023-08-25 12:33:06907瀏覽

在Java 9中,我们可以在接口中使用私有方法吗?

是的,自Java9起,您可以在介面中使用私有方法。

範例

interface MyInterface {
   public abstract void demo();
   public default void defaultMethod() {
      privateMethod();
      staticPrivateMethod();
      System.out.println("This is a default method of the interface");
   }
   public static void staticMethod() {
      staticPrivateMethod();
      System.out.println("This is a static method of the interface");
   }
   private void privateMethod(){
      System.out.println("This is a private method of the interface");
   }
   private static void staticPrivateMethod(){
      System.out.println("This is a static private method of the interface");
   }
}
public class InterfaceMethodsExample implements MyInterface {
   public void demo() {
      System.out.println("Implementation of the demo method");
   }
   public static void main(String[] args){
      InterfaceMethodsExample obj = new InterfaceMethodsExample();
      obj.defaultMethod();
      obj.demo();
      MyInterface.staticMethod();
   }
}

輸出

This is a private method of the interface
This is a static private method of the interface
This is a default method of the interface
Implementation of the demo method
This is a static private method of the interface
This is a static method of the interface

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

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