Java 将类强制转换为不相关的接口
显然,这会导致编译错误,因为椅子与Cat无关:Java 将类强制转换为不相关的接口,java,interface,casting,compilation,runtime,Java,Interface,Casting,Compilation,Runtime,显然,这会导致编译错误,因为椅子与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引用转换为不相关的接口家具时,我
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引用转换为不相关的接口家具时,我才会得到一个异常,而编译器显然可以告诉我Cat没有实现家具
interface Furniture {}
class Test {
public static void main(String[] args) {
Furniture f; Cat cat = new Cat();
f = (Furniture)cat; //runtime error
}
}
这是因为
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
实例,可以将其指定给catcat
,该实例可以强制转换为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
扩展,因为多态性发生在运行时。但是编译器知道Cat不实现家具,并且在运行时不能更改?我可能遗漏了一个简单的问题,但你的回答对我没有帮助,因为。尽管Cat可能不会直接实现家具,但Cat的某些超类可能会实现。编译器选择不深入这些丑陋的细节,因为接口的规则非常复杂。(谢谢你,Sun。)并且没有一般规则要求编译器检测不可避免的运行时异常(如被零除)——它更像是它提供的一种“服务”。需要注意的是,如果Cat
被声明为final
,编译器确实会抱怨(它知道,Cat
的子类不能实现Furniture
,因为不可能有Cat
的子类)。