Java介面中的預設方法與靜態方法有何區別?


Java中的介面類似於類,但是它只包含抽象方法和宣告為final和static的欄位。

從Java 8開始,介面中引入了靜態方法和預設方法。

預設方法 - 與其他抽象方法不同,這些方法可以有預設實現。如果介面中存在預設方法,則無需在已實現此介面的類中強制覆蓋(提供方法體)。

簡而言之,您可以使用實現類的物件訪問介面的預設方法。

示例

interface MyInterface{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface");
   }
}
public class InterfaceExample implements MyInterface{
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}

輸出

display method of MyInterface

靜態方法 - 它們使用static關鍵字宣告,並將與介面一起載入到記憶體中。您可以使用介面名稱訪問靜態方法。

如果您的介面具有靜態方法,則需要使用介面的名稱來呼叫它,就像類的靜態方法一樣。

示例

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

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

靜態方法和預設方法的區別:

呼叫方法

  • 您可以使用介面的名稱呼叫靜態方法。
  • 要呼叫預設方法,您需要使用實現類的物件。

覆蓋方法

  • 如果需要,您可以從實現類中覆蓋介面的預設方法。

示例

interface MyInterface{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface");
   }
}
public class InterfaceExample implements MyInterface{
   public void display() {
      System.out.println("display method of class");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}

輸出

display method of class
  • 您不能覆蓋介面的靜態方法;您只能使用介面的名稱訪問它們。如果您嘗試透過在實現介面中定義類似的方法來覆蓋介面的靜態方法,則它將被視為類的另一個(靜態)方法。

示例

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

輸出

Static method of the interface
Static method of the class

更新於:2020年7月2日

8K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告