工作,我寫了下面的代碼:多態性不能在方法的參數在Java中
class Plane {}
class Airbus extends Plane {}
public class Main {
void fly(Plane p) {
System.out.println("I'm in a plane");
}
void fly(Airbus a) {
System.out.println("I'm in the best Airbus!");
}
public static void main(String[] args) {
Main m = new Main();
Plane plane = new Plane();
m.fly(plane);
Airbus airbus = new Airbus();
m.fly(airbus);
Plane planeAirbus = new Airbus();
m.fly(planeAirbus);
}
}
,其結果是:
I'm in a plane
I'm in the best Airbus!
I'm in a plane
不出所料前兩個調用分別給出I'm in a plane
和I'm in the best Airbus!
。
Plane planeAirbus = new Airbus();
該方法將此對象視爲平面,即使真實對象是空中客車。即使當我添加abstract
到class Plane
,沒有什麼變化和上次調用的結果仍然是I'm in a plane
所以,問題是爲什麼多態性不能在工作方法的參數和調用?這有什麼目的嗎?它是如何工作的?
是其他名字動態綁定雙調度還是有不同的概念? –
我認爲雙重調度是不同的,但雙重調度通常也實現動態綁定,所以他們經常在一起看到。 – markspace
Double Dispatch可以通過使用Visitor模式在Java中實現,因爲Java是一種靜態類型語言。 – Timmos