public static final。public,實現類必須 public 實現。
interface Instrument5 {
int i = 5; // 編譯期常數
void play(); String what(); void adjust();
}
class Wind5 implements Instrument5 { ... }
class Percussion5 implements Instrument5 { ... }
class Stringed5 implements Instrument5 { ... }
class Brass5 extends Wind5 { ... } // 繼承具體類並實現接口
class Woodwind5 extends Wind5 { ... }
static void tune(Instrument5 i) { i.play(); }
static void tuneAll(Instrument5[] e) { for (Instrument5 ins : e) tune(ins); }
Instrument5[] orchestra = { new Wind5(), new Percussion5(), new Stringed5(), new Brass5(), new Woodwind5() };
tuneAll(orchestra);
tune() 僅依賴 Instrument5 接口,新增樂器類型(如 Electronic5)零修改 即可納入體系。接口建立了「協議」,實現類遵守協議,框架代碼穩定不變。
對調用者而言,Instrument5 是接口、抽象類還是普通類完全透明。多態機制統一處理。差異僅在於「創建與使用的控制力度」: