这是问题(答案显然是1):
考虑以下课程:
interface I{
}
class A implements I{
}
class B extends A {
}
class C extends B{
}
以下声明:
A a = new A();
B b = new B();
识别将编译并运行且没有错误的选项:
a = (B)(I)b;
b = (B)(I) a;
a = (I) b;
I i = (C) a;
提前感谢您的帮助! :)
答案 0 :(得分:2)
1很好,但分别运行时出现2,3和4错误。
从代码中,我们可以注意到以下关系,我使用->
来表示扩展或实现(也就是说,它们可以在箭头方向上转换)
C -> B -> A -> I
variable a is of type A
variable b is of type B
使用括号显式转换是运行时检查。在编译时检查赋值的左侧和右侧不匹配时发生的隐式转换。
使用上述信息,我们可以查看每个陈述并得出以下结论:
1. a = (B)(I)b; // OK
The target assignment is of type A. b is runtime castable to I,
I is runtime castable to B and B is compile time castable to A.
2. b = (B)(I) a; // RUNTIME ERROR
The target assignment is of type B. a is runtime castable to I, but
A is not runtime castable to B.
3. a = (I) b; // COMPILE ERROR
The target assignment is of type A. b is runtime castable to I but I cannot
be cast at compile time to A.
4. I i = (C) a; // RUNTIME ERROR
The target assignment is of type I. a is not runtime castable to C but C
is compile time castable to I.