我有以下的代码,其中包含了一个父类和它的子类。我尝试确定在使用多态性方面这段代码的好处。
class FlyingMachines {
public void fly() {
System.out.println("No implementation");
}
}
class Jet extends FlyingMachines {
public void fly() {
System.out.println("Start, Taxi, Fly");
}
public void bombardment() {
System.out.println("Throw Missile");
}
}
public class PolymorphicTest {
public static void main(String[] args) {
FlyingMachines flm = new Jet();
flm.fly();
Jet j = new Jet();
j.bombardment();
j.fly();
}
}
当flm.fly()
和j.fly()
给我同样的答案时,多态的优点是什么?
flm.fly();
评估为:System.out.println("No implementation");
... Java虚拟机在运行时将看到flm.fly();
评估为:System.out.println("Start, Taxi, Fly");
... 如果您将第20行从flm.fly();
更改为flm.bombardment();
,则会出现编译错误,因为bombardment()
消息不是FlyingMachines
协议的一部分。 - Jack_Hu