Java 中 Interface 包含哪些內容


可以使用 interface 關鍵字定義介面。它包含變數和方法,與類相似,但介面中的方法與類不同,預設情況下是抽象的。介面主要用於實現抽象,且無法例項化。

下面給出示例程式,演示 Java 中的介面

示例

 線上演示

interface AnimalSound {
   abstract void sound();
}
class CatSound implements AnimalSound {
   public void sound() {
      System.out.println("Cat Sound: Meow");
   }
}
class DogSound implements AnimalSound {
   public void sound() {
      System.out.println("Dog Sound: Bark");
   }
}
class CowSound implements AnimalSound {
   public void sound() {
      System.out.println("Cow Sound: Moo");
   }
}

public class Demo {
   public static void main(String[] args) {
      AnimalSound a = new CatSound();
      a.sound();
   }
}

輸出

Cat Sound: Meow

更新時間:2019 年 07 月 30 日

241 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.