【发布时间】:2015-03-01 18:17:24
【问题描述】:
我了解以下代码的工作原理,基于多态性和动态绑定。 Java 能够在运行时以某种方式计算出,因为 vh 是一个 MotorBike,我们应该调用 MotorBike 的 move() 方法。
class Vehicle{
public void move(){
System.out.println(“Vehicles can move!!”);
}
}
class MotorBike extends Vehicle{
public void move(){
System.out.println(“MotorBike can move and accelerate too!!”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // prints MotorBike can move and accelerate too!!
}
}
我不明白为什么以下代码会中断。我所做的唯一更改是从 Vehicle 类中删除 move() 方法。现在我收到一个编译错误,上面写着“找不到符号 - 方法 move()”。为什么会这样?为什么前面的示例有效而这段代码无效?
class Vehicle{
}
class MotorBike extends Vehicle{
public void move(){
System.out.println(“MotorBike can move and accelerate too!!”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // compile error
}
}
【问题讨论】:
-
因为您已经告诉编译器
vh引用指向Vehicle,并且所有Vecicle都没有move()方法。
标签: java inheritance late-binding