我写了下面这段代码:
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不支持方法参数的动态绑定(bind)。您看到的是静态绑定(bind),即在编译时选择要调用的方法的重载。
关于java - 多态性在 Java 中的方法参数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722057/