以下代码段将导致运行时:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么会导致运行时错误而不是编译错误?难道编译器不应该知道'v'已经是'Car'并且不能被投入'Bike'吗?
为什么Java中可以使用以下内容?
Integer[] ints = (Integer[])new Comparable[10];
Run Code Online (Sandbox Code Playgroud)
但它ClassCastException在运行时获得.new接口数组的用例是什么?