为什么向下倾倒抛出异常? [英] Why Downcasting throws Exception?
问题描述
在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屋!