爪哇的多个铸造
我知道有关Java如何执行铸件的一些规则,但是我无法在以下示例中弄清楚规则:
interface I {}
class A implements I {}
class B extends A {}
class C extends B {}
class DriverClass {
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
a = (A)(B)(C)c; // line 1 - Valid
a = (A)(C)(B)c; // line 2 - Valid
a = (B)(A)(C)c; // line 3 - Valid
a = (B)(C)(A)b; // line 4 - Runtime error
a = (C)(B)(A)b; // line 5 - Runtime error
a = (C)b; // line 6 - Runtime error
}
}
有人可以解释为什么第1行3行是有效的语句,而第4行到第6行的第4行,classcastException的运行时错误?
I know some rules around how Java performs the casting but I am unable to figure out the rules in the following example:
interface I {}
class A implements I {}
class B extends A {}
class C extends B {}
class DriverClass {
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
a = (A)(B)(C)c; // line 1 - Valid
a = (A)(C)(B)c; // line 2 - Valid
a = (B)(A)(C)c; // line 3 - Valid
a = (B)(C)(A)b; // line 4 - Runtime error
a = (C)(B)(A)b; // line 5 - Runtime error
a = (C)b; // line 6 - Runtime error
}
}
Can someone please explain why line 1 to line 3 are valid statements whereas line 4 to line 6 throw Runtime Error of ClassCastException?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的课程声明说每个C是A B,每个B(包括C)都是
A。可以按任何顺序将
c
施加到这三个类中的任何一个中,并且不会出现错误。然后,您使
b
引用新B,这不是C。这意味着您可以将其施放给A或B,而无需任何问题,但是一旦您尝试施放b
对于C,您会遇到错误,因为B
引用的对象不是C。Your class declaration says that every C is a B and every B (including the C's) is an A.
Now you make
c
reference a new C, so it's also a B and an A. That means you can castc
to any of the three classes, in any order, and there won't be an error.Then you make
b
reference a new B, that's not a C. That means you can cast it to A or B without any problems, but as soon as you try to castb
to C, you get an error, because the object referenced byb
is not a C.