简体   繁体   English

有关铸造的Java 803考试

[英]Java 803 exam regarding casting

in preparation for the 803 exam, I came across a question that really stumped me since I hadn't seen this been done until then. 在为803考试做准备时,我遇到了一个真正困扰我的问题,因为直到那时我还没有看到这样做。 The answer to the question confused me even more - can anyone kindly explain exactly what is happening here? 这个问题的答案让我更加困惑-有人能解释一下这里发生了什么吗?

Here is the question (the answer is 1 apparently): 这是问题(答案显然是1):


Consider the following classes : 考虑以下类别:

interface I{
}
class A implements I{
}

class B extends A {
} 

class C extends B{
}

And the following declarations: 以及以下声明:

A a = new A();

B b = new B(); 

Identify option that will compile and run without error: 确定将编译并无错误运行的选项:

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

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

  3. a = (I) b;

  4. I i = (C) a;

Thanks in advance for your help! 在此先感谢您的帮助! :) :)

1 is fine, but when run separately 2, 3 and 4 error. 1很好,但是分别运行2,3和4时出错。

From the code, we can note the following relationships, I have used -> to mean extends or implements (that is, they are castable in the direction of the arrow) 从代码中,我们可以注意到以下关系,我曾使用->表示扩展或实现(即,它们可沿箭头方向浇铸)

C -> B -> A -> I

variable a is of type A
variable b is of type B

Explicit casting using brackets is a runtime check. 使用方括号的显式转换是运行时检查。 Implicit casting, as happens when the left and right hand sides of the assignment do not match is checked at compile time. 在编译时检查隐式强制转换(当赋值的左侧和右侧不匹配时会发生这种情况)。

Using the information above we can look at each of the statements and make the following conclusions: 使用以上信息,我们可以查看每个语句并得出以下结论:

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM