介面(Interface)是抽象型別、抽象方法集合,以 interface 宣告。類別透過 implements 實作介面,繼承其抽象方法。
.java 檔,檔名即介面名.class 位元碼檔public abstract)static final 常數)public abstract(其他修飾符會編譯錯誤)public static final(private 會編譯錯誤)| 差異點 | 抽象類別 | 介面 |
|---|---|---|
| 方法主體 | 可有方法主體(具體實作) | 不可有方法主體 |
| 成員變數型別 | 任意型別 | 僅 public static final |
| 靜態區塊/方法 | 可有 | 不可有(Java 8 前) |
| 繼承/實作限制 | 單一繼承 | 可多重實作 |
[visibility] interface InterfaceName [extends OtherInterface] {
// 常數欄位
// 抽象方法
}
public interface NameOfInterface {
// 任何型別 final static 欄位
// 抽象方法
}
interface Animal {
void eat();
void travel();
}
類別需實作介面所有方法,否須宣告為抽象類。語法:
class ClassName implements InterfaceName[, OtherInterface...] { ... }
public class MammalInt implements Animal {
public void eat() { System.out.println("Mammal eats"); }
public void travel() { System.out.println("Mammal travels"); }
public int noOfLegs() { return 0; }
public static void main(String[] args) {
MammalInt m = new MammalInt(); m.eat(); m.travel();
}
}
Mammal eats Mammal travels
介面可繼承介面,使用 extends,子介面繼承父介面方法。
public interface Sports { void setHomeTeam(String name); void setVisitingTeam(String name); }
public interface Football extends Sports { void homeTeamScored(int pts); void visitingTeamScored(int pts); void endOfQuarter(int q); }
public interface Hockey extends Sports { void homeGoalScored(); void visitingGoalScored(); void endOfPeriod(int p); void overtimePeriod(int ot); }
實作 Hockey 需實作 6 個方法(4 自有 + 2 繼承),實作 Football 需 5 個。
類別多重繼承非法,但介面允許:
public interface Hockey extends Sports, Event { ... }
無任何方法與屬性的介面,如 java.util.EventListener:
package java.util;
public interface EventListener {}