关于铸造的Java803考试
在准备803考试时,我遇到了一个问题,这个问题真的让我很难受,因为直到那时我才看到这个问题被解决了。这个问题的答案让我更加困惑——谁能解释一下这里到底发生了什么 以下是问题(答案显然是1):关于铸造的Java803考试,java,casting,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(); 确定将编译并运行而不会出错的选项:
考虑以下类别:
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=(C)a代码>
提前感谢您的帮助!:) 1可以,但当分别运行2、3和4时会出现错误 从代码中,我们可以注意到以下关系,我使用了
->
来表示扩展或实现(也就是说,它们可以按箭头方向浇铸)
使用括号显式转换是一种运行时检查。在编译时检查隐式转换,如赋值的左侧和右侧不匹配时发生的情况
利用上述信息,我们可以查看每个陈述,并得出以下结论:
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.
那么什么让你困惑呢?3。。。b对我来说是可铸造的,但对b来说不是。这是正确的吗?@Jayde感谢你指出这一点,通过澄清哪些强制转换发生在运行时,哪些发生在编译时,这一行已经修复。没问题。这是一个非常全面的回答。
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.