Java interface 關鍵字
示例
interface
是一個抽象的“類”,用於將具有“空”主體的相關方法分組
要訪問介面方法,該介面必須由另一個類使用 implements
關鍵字(而不是 extends
)來“實現”(有點像繼承)。介面方法的主體由“實現”類提供
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
定義和用法
interface
關鍵字用於宣告一種特殊型別的類,該類只包含抽象方法。
要訪問介面方法,該介面必須由另一個類使用 implements
關鍵字(而不是 extends
)來“實現”(有點像繼承)。介面方法的主體由“實現”類提供。
關於介面的說明
- 它不能用於建立物件(在上面的示例中,不可能在 MyMainClass 中建立 "Animal" 物件)
- 介面方法沒有主體——主體由“實現”類提供
- 在實現一個介面時,你必須覆蓋它的所有方法
- 介面方法預設是
abstract
和public
的 - 介面屬性預設是
public
、static
和final
的 - 介面不能包含建構函式(因為它不能用於建立物件)
為何以及何時使用介面?
為了實現安全性——隱藏某些細節,只顯示物件(介面)的重要細節。
Java 不支援“多重繼承”(一個類只能繼承一個超類)。然而,透過介面可以實現這一點,因為一個類可以實現多個介面。注意:要實現多個介面,請用逗號分隔它們(見下面的例子)。
多個介面
要實現多個介面,請用逗號將它們分開
示例
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
// DemoClass "implements" FirstInterface and SecondInterface
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
相關頁面
在我們的 Java 介面教程中閱讀更多關於介面的內容。