显然,这会导致编译错误,因为 Chair 与 Cat 无关:
class Chair {}
class Cat {}
class Test {
public static void main(String[] args) {
Chair chair = new Char(); Cat cat = new Cat();
chair = (Chair)cat; //compile error
}
}
那么为什么我只在运行时将 Cat 引用投射到不相关的接口 Furniture 时才得到异常,而编译器可以明显看出 Cat 没有实现 Furniture?
interface Furniture {}
class Test {
public static void main(String[] args) {
Furniture f; Cat cat = new Cat();
f = (Furniture)cat; //runtime error
}
}