多态在Java的方法参数中不起作用 [英] Polymorphism doesn't work in method arguments in Java
本文介绍了多态在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
推荐答案
这里的问题是JAVA不支持方法参数的动态绑定。您看到的是静态绑定,即在编译时选择要调用的方法的重载。
另见:Static Binding and Dynamic Binding
这篇关于多态在Java的方法参数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文