将超类转换为子类 [英] Cast a superclass to a subclass

查看:136
本文介绍了将超类转换为子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一个类扩展建筑物的村庄和代码

 建筑物Building = new Building() ; 
Cottage Cottage =(Cottage)building;

现在,建筑物完全不能转换为 Cottage 考虑到Java继承的性质,但是(对我而言)没有意义的是它可以编译。为什么要编译然后抛出运行时 ClassCastException



在实际运行程序之前,建筑物是否是对 Building 对象的引用? / p>

作为这样一个一般性的问题,我知道我可能对此重复:),但是找不到为什么它会编译问题的答案:)



EDIT2 我在这里接受了一个很好的答案(更不用说下面的讨论了了:)),但是我仍然在 Java转换导致运行时错误而不是编译错误最有趣的...



编辑我编辑了 IllegalCastException 并输入了正确的 ClassCastException

解决方案

这是因为,编译器不知道您引用的是哪个对象 Building 所指。



因此,在以下情况下,您有一个基类引用,指向 sub class 对象: -

 建筑物= new Cottage(); 
Cottage Cottage =(Cottage)building;

它会很好地工作。因此,关于它是否是有效的强制转换,这完全是 runtime 的决定。因此,编译器不会为此抛出错误。


建筑不是对建筑对象$ b $的引用是不是很明显

否。绝对不会。被引用的对象类型直到运行时才知道。请始终记住,编译器始终检查引用类型。在运行时检查实际的对象类型。



此概念称为多态性,在这里您可以使用相同的引用类型来指向对象各种子类型。您可以在Google上对其进行搜索,并会获得大量的阅读资源。


Imagine a class Cottage extending Building and the code

Building building = new Building();
Cottage cottage = (Cottage)building;

Now, it totally makes sense that Building cannot be casted to Cottage considering the nature of java's inheritance, but what doesn't make sense (to me) is that this compiles. Why does it compile and then throw a runtime ClassCastException?

Isn't it obvious that building is a reference to a Building object before actually running the program?

Being such a general question, I know I am getting a possible duplicate for this one :) but I couldn't find an answer to WHY DOES IT COMPILE question :)

EDIT2 I accepted a great answer here (let alone the discussion below it :) ), but I still find the accepted answer in Java casting resulting in run-time error instead of compilation error the most interesting...

EDIT I edited IllegalCastException and put the correct ClassCastException

解决方案

That's because, compiler does not know what object does your reference Building is referring to.

So, in the below case, where you have a base class reference, pointing to sub class object: -

Building building = new Cottage();
Cottage cottage = (Cottage)building;

It would work perfectly fine. So, it's completely a runtime decision, as to whether it is a valid cast or not. Hence, compiler won't throw error for that.

Isn't it obvious that building is a reference to a Building object before actually running the program?

No. Absolutely not. The type of object being referenced, is not known till runtime. Always remember that, Compiler always checks the reference type. Actual object type is checked at runtime.

This concept is known as Polymorphism, where you can have the same reference type to point to objects of various subtypes. You can google it, and would get lots of resources to read.

这篇关于将超类转换为子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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