将类转换为不相关的接口 [英] Casting a class to an unrelated interface
问题描述
很明显,这会导致编译错误,因为Chair与Cat无关:
Obviously, this results in a compilation error because Chair is not related to 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吗?
Why is it then that I only get an exception at run time when I cast a Cat reference to the unrelated interface Furniture, while the compiler can obviously tell that Cat does not implement Furniture?
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
实例,则可以将其分配给 Cat cat
,该实例可以强制转换为家具
。换句话说,某些 Cat
子类型可能实现了 Furniture
接口。
If you create a CatFurniture
instance, you can assign it to Cat cat
and that instance can be casted to Furniture
. In other words, it's possible that some Cat
subtype does implement the Furniture
interface.
第一个示例
class Test {
public static void main(String[] args) {
Chair chair = new Char(); Cat cat = new Cat();
chair = (Chair)cat; //compile error
}
}
有些 Cat
子类型扩展了 Chair
,除非 Cat
本身从主席
。
it's impossible that some Cat
subtype extends Chair
unless Cat
itself extends from Chair
.
这篇关于将类转换为不相关的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!