Java继承downcast ClassCastException [英] Java inheritance downcast ClassCastException

查看:132
本文介绍了Java继承downcast ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码,我有一个问题:

given the following code, I have a question:

class A{}
class B extends A {}
class C extends B{}

public class Test {
    public static void main(String[] args) {
        A a = new A();
        A a1=new A();
        B b = new B();
//        a=b;// ok
//        b=(B)a;// ClassCastException
//        a=(A)a1;  // ok
//        a=a1;  // ok

        a=(B)a1;  // compiles ok, ClassCastException
    }
}

我的问题是粗体线。我的理解是,对于要编译的代码,只需要满足这些类在同一层次结构中,因此它可以工作(在树上隐式转换,在树下需要显式转换)。
每当我遇到ClassCastException时,都是因为引用指向树上的一个对象,例如指向类型A的对象的类型B的引用。

My question is with the line in bold. My understanding is that for the code to compile, it just needs to be satisfied that the classes are in the same hierarchy and as a result it may work (up the tree implicit casting, down the tree requires explicit casting). Whenever I have come across ClassCastException it is because the reference was pointing to an object up the tree e.g. a ref of type B pointing to an object of type A.

有问题的行似乎是指向类型A的对象的类型A的引用。到(B)显然是导致ClassCastException的原因。有人可以解释一下它的作用是什么吗?

The line in question appears to be a ref of type A pointing to an object of type A. The cast to (B) obviously is what is causing the ClassCastException. Can someone explain please what it does to effect this?

注意:如果a1指向B类型的对象,那么它可以工作(只是测试它)。因此,对于编译器来说,向下转换是合法的,如果引用指向正确类型的对象,则可以使其无异常地执行。

Note: If a1 was pointing at an object of type B then it works (just tested it). So the downcast is legal regarding the compiler and it can be made to execute without an exception if the reference is pointing at an object of the correct type.

通过转换A ref a1到a B并将其分配给a,看来A ref a不再期望引用A类对象而是B对象?

By casting the A ref a1 to a B and assigning it to a, it appears that the A ref a no longer expects to refer to an object of type A but a B?

谢谢,
Sean。

Thanks, Sean.

PS我知道这有点不寻常,为Java认证做准备。通常我们向下转到左侧的类型,例如B =(B)一个; (我可以看出为什么会产生ClassCastException)。

PS I know this is a bit unusual, preparation for Java certification. Normally we downcast to the type on the left hand side e.g. b=(B)a; (and I can see why this gives a ClassCastException).

推荐答案

所有B都是A,通过继承。但并非所有的A都是B的。这个特定的实例不是,因此是运行时异常。

All B's are A's, by inheritance. But not all A's are B's. This particular instance isn't, hence the runtime exception.

这篇关于Java继承downcast ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆