爪哇的多个铸造

发布于 2025-02-07 02:28:53 字数 650 浏览 4 评论 0原文

我知道有关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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗恋未遂 2025-02-14 02:28:53

您的课程声明说每个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 cast c 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 cast b to C, you get an error, because the object referenced by b is not a C.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文