| 類別 | 定義 | 特征 | 用途 |
|---|---|---|---|
| 啞接口 | 類的 public/protected 方法集合 | 無關鍵字,隱式契約 | 類的對外服務邊界 |
| 抽象接口 | 類的 abstract 方法集合 | 強制子類實現,定義行為規範 | 框架擴展點、模板方法 |
| 接口類 | interface 關鍵字聲明 | 本質是特殊類,可繼承、可多態、可標註註解 | 類型契約、多實現切換、SPI |
| 維度 | 抽象類 | 接口類 |
|---|---|---|
| 關鍵字 | abstract class | interface |
| 字段 | 可定義實例字段、非 final | 僅 static final 常量 |
| 構造器 | 有(子類調用 super()) | 無 |
| 方法實現 | 可有非抽象方法 | Java 8 前全抽象,8+ 支持 default/static |
| 繼承關係 | 單繼承 | 多實現、多繼承 |
| 設計意圖 | is-a 關係,共享狀態與邏輯 | can-do 契約,定義能力邊界 |
業務接口 action,實現類 Man、Man2。委託類 Delegate 需統一調用 action.run(),但持有的是具體實現對象。引入適配器 Adapter 利用接口向上轉型實現解耦。
// 接口契約
interface action { void run(); }
// 基類
abstract class Human {
abstract void shape();
Human() { System.out.println("Human()"); }
}
// 實現類
class Man extends Human implements action {
void shape() { System.out.println("man.shape()"); }
Man() { System.out.println("man()"); shape(); }
public void run() { System.out.println("man.run()"); }
}
class Man2 extends Human implements action {
void shape() { System.out.println("man2.shape()"); }
Man2() { System.out.println("man2()"); shape(); }
public void run() { System.out.println("man2.run()"); }
void sex() {} // 擴展方法
}
// 委託調用者
class Delegate {
void run(action act) { act.run(); } // 面向接口編程
}
// 適配器:將任意 Object 適配為 action
class Adapter implements action {
private action target;
Adapter(Object obj) { target = (action) obj; } // 向上轉型,利用多態
public void run() { target.run(); }
}
// 客戶端
public class MyInterface {
public static void main(String[] args) {
Man man = new Man();
man.run(); // 直接調用
Delegate de = new Delegate();
de.run(new Adapter(man)); // 適配器模式:Delegate 無需知道 Man 具體類型
}
}
Human() man.shape() man() man.run() Human() man.shape() man() man.run()
Delegate.run(action) 依賴抽象,而非具體實現。Adapter 構造器接收 Object,強轉為 action,運行時綁定具體實現。Man2 有額外方法 sex(),Delegate 完全不知情,擴展不影響調用方。Man() 調用 shape() 觸發子類實現,體現模板方法雛形。default 方法:接口提供默認實現,不破壞現有實現類(如 Collection.stream())。static 方法:接口級工具方法(如 Comparator.naturalOrder())。private 方法:default 方法間復用邏輯。接口是 Java 實現多態、解耦、擴展的核心機制。從啞接口到接口類,從單實現到默認方法,接口不斷進化以適應更靈活的架構需求。掌握接口分類、抽象類對比、代理適配器等經典模式,是寫出高內聚、低耦合代碼的關鍵。