首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 向上轉型基礎:Instrument 與 Wind 的繼承關係與 tune() 方法

     編輯:Java 相關知識

向上轉型定義

將衍生類引用賦值給基類引用:Instrument i = new Wind();。繼承樹畫法基類在上,故稱「向上」。

安全性保證

  • 衍生類包含基類所有方法(繼承而來),接口至少不縮小。
  • 編譯器允許隱式向上轉型,無需顯式造型。
  • tune(Instrument i) 內調用 i.play(),Wind 繼承了 play(),絕對安全。

Music 完整代碼

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); // 隱式向上轉型
    }
}

運行流程

  1. main 創建 Wind 對象,引用類型 Wind。
  2. 調用 tune(flute),flute 隱式向上轉型為 Instrument 引用傳入。
  3. tune 內調用 i.play(Note.middleC)。
  4. 動態綁定:實際對象是 Wind → 執行 Wind.play() → 輸出 "Wind.play()"。

關鍵認知

向上轉型不丟失對象實際類型,僅改變引用的靜態類型。運行期多態機制依然能找到正確方法。這是多態運作的前提條件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved