Java 中可以為介面建立物件嗎?


不,您不能例項化介面。通常,它包含抽象方法(除了 Java8 中引入的預設方法和靜態方法),這些方法是不完整的。

如果您仍然嘗試例項化介面,則會生成編譯時錯誤,提示“MyInterface 是抽象的;無法例項化”。

在以下示例中,我們有一個名為 MyInterface 的介面和一個名為 InterfaceExample 的類。

在介面中,我們有一個整數字段(公共、靜態和最終)num 和抽象方法 demo()

從類中,我們嘗試 - 建立介面的物件並列印 num 值。

示例

 線上演示

interface MyInterface{
   public static final int num = 30;
   public abstract void demo();
}
public class InterfaceExample implements MyInterface {
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      MyInterface interfaceObject = new MyInterface();
      System.out.println(interfaceObject.num);
   }
}

編譯時錯誤

編譯上述程式時,會生成以下錯誤

輸出

InterfaceExample.java:13: error: MyInterface is abstract; cannot be instantiated
   MyInterface interfaceObject = new MyInterface();
^
1 error

要訪問介面的成員,您需要實現它併為其所有抽象方法提供實現。

示例

 線上演示

interface MyInterface{
   public int num = 30;
   public void demo();
}
public class InterfaceExample implements MyInterface {
   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();
      System.out.println(MyInterface.num);
   }
}

輸出

This is the implementation of the demo method
30

更新於: 2020-06-29

16K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.