父類 Bird
public class Bird {
public void move(){
System.out.println("this is bird class move method ... ");
}
}
子類 Goose
public class Goose extends Bird {
@Override
public void move() {
System.out.println("this is Goose class move method ... ");
}
}
子類 Penguin
public class Penguin extends Bird {
@Override
public void move() {
System.out.println("this is Penguin class move method ... ");
}
}
調用類,參數類型為 Bird
public class BirdController {
public void reLocate(Bird bird) {
bird.move();
}
}
測試
public class Test {
public static void main(String[] args) {
/**
* 雖然 BirdController 中的 reLocate 方法的參數聲明的是必須傳入一個 Bird 類型的對象。
* 但是其 Bird 類的兩個子類 Goose 和 Penguin 依然也可以傳入到該方法中,并正確運行。
* 面向對象程序語言中使用了 "后期綁定" 這一概念。
* 即在程序運行時,才能知道被調用方法的代碼在計算機中的地址。
* 與此同時,進行參數和返回值的類型檢查。
* 這種概念也成為 "動態綁定"。
* 在 Java 中,動態綁定是自動執行的。不需要人工干預。
* 如 C++ 中,需要借助 "virtual" 關鍵字來達到同樣的目的。
*/
BirdController controller = new BirdController();
Bird bird = new Bird();
Goose goose = new Goose();
Penguin penguin = new Penguin();
/**
* "goose"、"penguin" 均為 Bird 的子類對象,但是卻可以自動向上轉型為 Bird 對象。
*/
controller.reLocate(bird);
controller.reLocate(goose);
controller.reLocate(penguin);
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。