宣告和實現介面
使用 interface 關鍵字宣告介面:
public interface Animal {
    String getSound(); // Interface methods are public by default
}
覆蓋註釋
@Override
public String getSound() {
    // Code goes here...
}
這會強制編譯器檢查我們是否重寫並阻止程式定義新方法或弄亂方法簽名。
介面使用 implements 關鍵字實現。
public class Cat implements Animal {
    @Override 
    public String getSound() {
        return "meow";
    }
}
public class Dog implements Animal {
    @Override
    public String getSound() {
        return "woof";
    }
}
在示例中,類 Cat 和 Dog 必須定義 getSound() 方法,因為介面的方法本質上是抽象的(預設方法除外)。
使用介面
Animal cat = new Cat();
Animal dog = new Dog();
System.out.println(cat.getSound()); // prints "meow"
System.out.println(dog.getSound()); // prints "woof"