正如您所指出的,这将编译:
interface MyInterface {}
class A {}
public class InterfaceCasting {
public static void main(String[] args) {
MyInterface myObject = new MyInterface() {};
A a = (A) myObject;
}
}
但是,这不会编译:
interface MyInterface {}
class A {}
public class InterfaceCasting {
public static void main(String[] args) {
A a = (A) new MyInterface() {}; // javac says: "inconvertible types!"
}
}
那么,这是怎么回事呢?有什么区别?
好吧,由于它只是一个接口,它很可能由扩展A的类实现,在这种情况下,从到的转换将是合法的。MyInterface
MyInterface
A
例如,此代码将在所有执行的 50% 中成功,并说明编译器需要解决可能不可判定的问题,以便始终在编译时“检测”非法强制转换。
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;
}
}