如何在 Java 中類裡面編寫/宣告介面?


Java 中的介面是對方法原型的規範。每當您需要指導程式設計師或簽訂合同以指定型別的方法和欄位時,就可以定義一個介面。

要建立這種型別的物件,您需要實現此介面,為介面的所有抽象方法提供正文並獲取實現類的物件。

巢狀介面

Java 允許在另一個介面內或在一個類內編寫/宣告介面,這些介面被稱為巢狀介面。

示例

在以下 Java 示例中,我們有一個名為 Sample 的類,它包含一個名為 myInterface 的巢狀介面。

在 Sample 類中,我們定義了一個名為 InnerClass 的巢狀類並實現了巢狀介面。

 即時演示

public class Sample {
   interface myInterface{
      void demo();
   }
   class InnerClass implements myInterface{
      public void demo(){
         System.out.println("Welcome to Tutorialspoint");
      }
   }
   public static void main(String args[]){
      InnerClass obj = new Sample().new InnerClass();
      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();
   }
}

輸出

Hello welcome to tutorialspoint

上次更新: 2020 年 6 月 29 日

769 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.