為什麼介面在 Java 中不能實現另一個介面?


在 Java 中,一個介面不能實現另一個介面。

  • Java 中的介面本質上是一種特殊的類。和類一樣,介面包含方法和變數。與類不同的是,介面總是完全抽象的。

  • 介面的定義就像類,只不過把 class 關鍵字換成了 interface,介面中宣告的變數是靜態的、最終的,介面中定義的方法是公共抽象方法。

  • 一個介面可以擴充套件任意數量的介面,但一個介面不能實現另一個介面,因為如果某個介面被實現了,那麼它的方法就必須明確定義,而介面永遠沒有對任何方法的明確定義。

  • 如果我們嘗試用另一個介面實現一個介面,那麼它將在 Java 中引發一個編譯時錯誤。

示例

interface MainInterface {
   void mainMethod();
}
interface SubInterface extends MainInterface { // If we put implements keyword in place of extends,                                               // compiler throws an error.
   void subMethod();
}
class MainClass implements MainInterface {
   public void mainMethod() {
      System.out.println("Main Interface Method");
   }
   public void subMethod() {
      System.out.println("Sub Interface Method");
   }
}
public class Test {
   public static void main(String args[]) {
      MainClass main = new MainClass();
      main.mainMethod();
      main.subMethod();
   }
}

輸出

Main Interface Method
Sub Interface Method

更新日期:2023 年 11 月 22 日

1.1 萬+ 瀏覽量

職業道路起航

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.