Java 介面
介面
在 Java 中實現抽象的另一種方法是使用介面。
介面是一個完全“抽象類”,用於將相關方法分組,這些方法具有空的方法體。
示例
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
要訪問介面方法,該介面必須由另一個類使用 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 Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
關於介面的說明
- 與抽象類一樣,介面不能用於建立物件(在上面的示例中,無法在 MyMainClass 中建立“Animal”物件)。
- 介面方法沒有方法體——方法體由“實現”類提供。
- 在實現一個介面時,你必須覆蓋它的所有方法
- 介面方法預設是
abstract和public的 - 介面屬性預設是
public、static和final的 - 介面不能包含建構函式(因為它不能用於建立物件)
為何以及何時使用介面?
1) 實現安全性——隱藏某些細節,只顯示物件(介面)的重要細節。
2) Java 不支援“多重繼承”(一個類只能繼承自一個超類)。然而,可以透過介面實現多重繼承,因為一個類可以實現多個介面。注意:要實現多個介面,請用逗號將它們分隔開(請參閱下面的示例)。
多個介面
要實現多個介面,請用逗號將它們分開
示例
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}