我們可以在 Java 類中定義介面嗎?


是的,你可以定義一個內部類,稱為巢狀介面。你不能直接訪問一個巢狀介面;你需要透過內部類或透過持有這個巢狀介面的類的名稱來訪問(實現)這個巢狀介面。

示例

現場演示

public class Sample {
   interface myInterface {
      void demo();
   }
   class Inner implements myInterface {
      public void demo() {
         System.out.println("Welcome to Tutorialspoint");
      }
   }
   public static void main(String args[]) {
      Inner obj = new Sample().new Inner();
      obj.demo();
   }
}

輸出

Welcome to Tutorialspoint

你也可以使用類名訪問巢狀介面,如下 −

示例

class Test {
   interface myInterface {
      void demo();
   }
}
public class Sample implements Test.myInterface {
   public void demo() {
      System.out.println("Hello welcome to tutorialspoint");
   }
   public static void main(String args[]) {
      Sample obj = new Sample();
      obj.demo();
   }
}

更新日期:16-6-2020

6000 多次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.