將衍生類引用賦值給基類引用:Instrument i = new Wind();。繼承樹畫法基類在上,故稱「向上」。
tune(Instrument i) 內調用 i.play(),Wind 繼承了 play(),絕對安全。
class Note { ... static final Note middleC = new Note(0); }
class Instrument { void play(Note n) { println("Instrument.play()"); } }
class Wind extends Instrument {
void play(Note n) { println("Wind.play()"); } // 覆寫
}
public class Music {
static void tune(Instrument i) { i.play(Note.middleC); }
public static void main(String[] args) {
Wind flute = new Wind();
tune(flute); // 隱式向上轉型
}
}
main 創建 Wind 對象,引用類型 Wind。tune(flute),flute 隱式向上轉型為 Instrument 引用傳入。tune 內調用 i.play(Note.middleC)。Wind → 執行 Wind.play() → 輸出 "Wind.play()"。向上轉型不丟失對象實際類型,僅改變引用的靜態類型。運行期多態機制依然能找到正確方法。這是多態運作的前提條件。