关于铸造的Java 803考试

时间:2014-11-10 12:54:09

标签: java casting

为了准备803考试,我遇到了一个让我感到困惑的问题,因为直到那时我还没有看到这个问题。这个问题的答案让我更加困惑 - 任何人都可以准确地解释这里发生了什么?

这是问题(答案显然是1):


考虑以下课程:

interface I{
}
class A implements I{
}

class B extends A {
} 

class C extends B{
}

以下声明:

A a = new A();

B b = new B(); 

识别将编译并运行且没有错误的选项:

  1. a = (B)(I)b;

  2. b = (B)(I) a;

  3. a = (I) b;

  4. I i = (C) a;

  5. 提前感谢您的帮助! :)

1 个答案:

答案 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.