显然,这会导致编译错误,因为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
}
}
答案 0 :(得分:12)
编译的原因
interface Furniture {}
class Test {
public static void main(String[] args) {
Furniture f; Cat cat = new Cat();
f = (Furniture)cat; //runtime error
}
}
是你很可能
public class CatFurniture extends Cat implements Furniture {}
如果您创建CatFurniture
实例,则可以将其分配给Cat cat
,并且该实例可以投放到Furniture
。换句话说,某些Cat
子类型可能会实现Furniture
接口。
在你的第一个例子中
class Test {
public static void main(String[] args) {
Chair chair = new Char(); Cat cat = new Cat();
chair = (Chair)cat; //compile error
}
}
除非Cat
本身从Chair
延伸,否则某些Cat
子类型无法扩展Chair
。