首頁  >  文章  >  Java  >  為什麼在Java中一個介面不能實作另一個介面?

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

WBOY
WBOY轉載
2023-08-19 23:45:07734瀏覽

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

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

  • 在Java中,介面本質上是一種特殊類型的類別。與類別一樣,介麵包含方法和變數。不同的是,介面始終是完全抽象的。
  • 介面的定義與類別類似,只是關鍵字interface取代了class,介面中宣告的變數是staticfinal的,在介面中定義的方法是public abstract方法。
  • 一個接口可以擴展任意數量的接口,但一個接口不能實現另一個接口,因為如果實現了任何接口,則必須定義其方法,而介面永遠不會有任何方法的定義。
  • 如果我們嘗試用另一個接口實作一個接口,在Java中會拋出編譯時錯誤。

範例

interface MainInterface {
   void mainMethod();
}
interface SubInterface extends MainInterface { // If we put <strong>implements </strong>keyword in place of <strong>extends,                                               </strong>// 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

以上是為什麼在Java中一個介面不能實作另一個介面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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