[英]Java Generics and Polymorphism - how to narrow down generic type at runtime
這是示例代碼:
public class Whatever
{
public static void main(String[] args)
{
LazyManufacturer manufacturer = new LazyManufacturer();
Porsche oldPorsche = new Porsche();
Porsche newPorsche = new Porsche();
manufacturer.updateCar(oldPorsche, newPorsche);
// for a car that I do not know the brand of, I would instantiate Car directly. So Car cannot be abstract
}
}
public class Car {
private String carCommonAttribute;
public void updateAccordingTo(Car car) {
carCommonAttribute = car.carCommonAttribute;
System.out.println("common updated");
}
}
public class Porsche extends Car {
private String porscheExclusiveAttribute;
public void updateAccordingTo(Porsche car) {
super.updateAccordingTo(car);
porscheExclusiveAttribute = car.porscheExclusiveAttribute;
System.out.println("porsche exclusive updated");
}
}
public class Garbage extends Car {
private String garbageAttribute;
// similar to Porsche
}
public class LazyManufacturer {
public <T extends Car> void updateCar(T oldCar, T newCar) {
oldCar.updateAccordingTo(newCar);
}
}
我知道這是一個不好的例子,但足以說明我要實現的目標。
現在,輸出為"common updated"
。 我也希望看到"porsche exclusive updated"
。
我知道在編譯時, startCar(car)
會認為Car
類中的start
方法是最合適的,因為其簽名與所要查找的內容完全匹配。 但是,有沒有一種方法可以在運行時解決該問題? 在運行時, startCar
會更適合start
方法,因為Porsche
是一種較窄的類型,不是嗎?
標記的意思是將Car-> start()方法更改為start()而不是start(Car)。 這樣,您將能夠實現自己的意圖。
通常,相同層次結構中的類應具有完全相同的方法簽名,以便它們覆蓋基類方法(僅當行為需要更改時,子類當然也可以具有更多方法)。 無需將Car實例傳遞給方法,因為對象始終可以訪問自身。 傳遞的參數沒有任何作用。 對於駕駛員來說,是的,駕駛員需要有一輛汽車作為輸入。 為什么汽車需要自身作為調用方法的輸入?
“在運行時,因為保時捷是一種較窄的車型,startCar會更適合啟動方法,不是嗎?”
是不是
在運行時,JVM沒有空閑時間根據給定參數的實際類型選擇最適合方法的方法。 根據聲明的參數類型,在編譯時選擇最佳擬合。
正如@markspace所說,您可能想要覆蓋start(),而不是對其進行重載。 為此,使Car.start()
和Porche.start()
簽名相同。 要么刪除參數(無論如何都不使用),或者在兩種情況下都將參數聲明為Car car
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.