Java类的接口 [英] Java Casting Interface to Class
问题描述
public class InterfaceCasting {
private static class A{}
public static void main(String[] args) {
A a = new A();
Serializable serializable = new Serializable(){};
a = (A)serializable;
}
}
编译成功,但运行时异常
Compilation succeed but Runtime exception
Exception in thread "main" java.lang.ClassCastException: InterfaceCasting$1 cannot be cast to InterfaceCasting$A
为什么要编译成功?编译器必须知道serialiazable不是A?
WHY COMPILATION SUCCEED? Compiler must known that serialiazable is not A?
推荐答案
正如你所指出的,
interface MyInterface {}
class A {}
public class InterfaceCasting {
public static void main(String[] args) {
MyInterface myObject = new MyInterface() {};
A a = (A) myObject;
}
}
编译:编译:
This however, will not compile:
interface MyInterface {}
class A {}
public class InterfaceCasting {
public static void main(String[] args) {
A a = (A) new MyInterface() {}; // javac says: "inconvertible types!"
}
}
有什么区别?
好吧,由于 MyInterface
只是一个接口, / em>非常好地通过扩展A 的类实现,在这种情况下,从 MyInterface
到 A
将是合法的。
Well, since MyInterface
is simply an interface, it could very well be implemented by a class that extends A, in which case the cast from MyInterface
to A
would be legal.
这段代码将在所有执行的50% / strong>,并说明编译器需要解决可能的不可判定的问题,以便在编译时总是检测非法的转换。
This code for instance, will succeed in 50% of all executions, and illustrates that the compiler would need to solve possibly undecidable problems in order to always "detect" illegal casts at compile time.
interface MyInterface {}
class A {}
class B extends A implements MyInterface {}
public class InterfaceCasting {
public static void main(String[] args) {
MyInterface myObject = new MyInterface() {};
if (java.lang.Math.random() > 0.5)
myObject = new B();
A a = (A) myObject;
}
}
这篇关于Java类的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!