Java 中的介面可以有靜態方法嗎?


Java 中的介面類似於類,但它只包含抽象方法和域,這些域是最終域和靜態域。

靜態方法使用 static 關鍵字來宣告,並且會隨類一起載入到記憶體中。你可以使用類名而不例項化來訪問靜態方法。

Java8 中介面中的靜態方法

從 Java8 開始,你可以在介面中使用靜態方法(帶主體)。你需要使用介面名稱來呼叫它們,就像呼叫類的靜態方法一樣。

示例

在以下示例中,我們在介面中定義了一個靜態方法,並從一個實現此介面的類中訪問它。

 線上演示

interface MyInterface{
   public void demo();
   public static void display() {
      System.out.println("This is a static method");
   }
}
public class InterfaceExample{
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.demo();
      MyInterface.display();
   }
}

輸出

This is the implementation of the demo method
This is a static method

更新時間:2020-06-29

7000+ 觀看數

啟動您的職業

完成課程進行認證

開始
廣告