从超类到子类的显式转换 [英] explicit casting from super class to subclass

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

问题描述

public class Animal {
    public void eat() {}
}

public class Dog extends Animal {
    public void eat() {}

    public void main(String[] args) {
        Animal animal = new Animal();
        Dog dog = (Dog) animal;
    }
}

赋值Dog dog = (Dog)animal;不会产生编译错误,但在运行时会产生ClassCastException.为什么编译器检测不到这个错误?

The assignment Dog dog = (Dog) animal; does not generate a compilation error, but at runtime it generates a ClassCastException. Why can't the compiler detect this error?

推荐答案

通过使用演员表,您实际上是在告诉编译器相信我.我是专业人士,我知道我在做什么,我知道虽然你不能保证,我告诉你,这个animal变量肯定会是一只狗."

By using a cast you're essentially telling the compiler "trust me. I'm a professional, I know what I'm doing and I know that although you can't guarantee it, I'm telling you that this animal variable is definitely going to be a dog."

由于动物实际上不是狗(它是动物,您可以执行 Animal animal = new Dog(); 并且它会是一只狗)VM 在运行时抛出异常因为你违反了这种信任(你告诉编译器一切都会好起来的,但事实并非如此!)

Since the animal isn't actually a dog (it's an animal, you could do Animal animal = new Dog(); and it'd be a dog) the VM throws an exception at runtime because you've violated that trust (you told the compiler everything would be ok and it's not!)

编译器比盲目地接受所有东西要聪明一点,如果您尝试将对象转换为不同的继承层次结构(例如,将 Dog 转换为 String),那么编译器会将其扔回给您,因为它知道永远不会可能工作.

The compiler is a bit smarter than just blindly accepting everything, if you try and cast objects in different inheritence hierarchies (cast a Dog to a String for example) then the compiler will throw it back at you because it knows that could never possibly work.

因为您本质上只是阻止编译器发出抱怨,所以每次进行强制转换时,通过使用 instanceof 在一个if 语句(或类似的东西.)

Because you're essentially just stopping the compiler from complaining, every time you cast it's important to check that you won't cause a ClassCastException by using instanceof in an if statement (or something to that effect.)

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

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