为什么向下倾倒抛出异常? [英] Why Downcasting throws Exception?

查看:98
本文介绍了为什么向下倾倒抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中:

Base b = new Base();
Derived d = (Derived)b; 

throws ClassCastException 。为什么?为什么向下投掷异常?我无法弄清楚原因。

throws ClassCastException. Why? Why downcasting throws Exception here? I could not figure out the reason.

推荐答案

让我重命名你的课程以使事情更加清晰。 Base - > Animal 派生 - > Cat

Let me rename your classes to make things more clear. Base -> Animal. Derived -> Cat.

仅仅因为你'重新动物并不意味着你是 Cat 。你可以是。这就是为什么将 Animal 投射到 Cat 中是违法的。

Just because you're an Animal doesn't mean you're a Cat. You could be a Dog. That's why it's illegal to cast an Animal into a Cat.

另一方面,每个 Cat Animal ?答案是肯定的。这就是你可以编写这样的代码的原因:

On the other hand, is every Cat an Animal? The answer is "yes". That's why you could write code like this:

Animal animal = new Cat();

Cat cat = new Cat();
Animal animal = cat;

另外值得注意的是你可以这样做:

Also what's worth noting is you can do this:

Animal animal = new Cat();
Cat cat = (Cat) animal;

你能做到这一点的原因是你的动物变量实际上是引用 Cat 实例。因此,您可以将其强制转换为引用 Cat 的变量。

The reason you can do this is that your animal variable is actually referencing a Cat instance. Therefore you're allowed to cast it back into a variable that references a Cat.

这篇关于为什么向下倾倒抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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