我們可以在 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();
   }
}

更新於: 6 月 16 日,2020 年

6K+ 次瀏覽

助力您的 職業

完成課程以取得資格認證

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