以下代码片段将导致运行时:
class Vehicle {
public void printSound() {
System.out.print("vehicle");
}
}
class Car extends Vehicle {
public void printSound() {
System.out.print("car");
}
}
class Bike extends Vehicle {
public void printSound() {
System.out.print("bike");
}
}
public class Test {
public static void main(String[] args) {
Vehicle v = new Car();
Bike b = (Bike) v;
v.printSound();
b.printSound();
}
}
我的问题是:为什么这会导致运行时错误而不是编译错误?编译器不应该知道'v'已经是'Car'并且不能转换成'Bike'吗?