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

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

问题描述

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

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

public void main(String [] args){
Animal animal = new Animal();
狗狗=(狗)动物;
}
}

作业 Dog dog = (Dog)动物; 不会生成编译错误,但在运行时它会生成 ClassCastException 。为什么编译器不能检测到这个错误?

解决方案

通过使用转换,你基本上告诉编译器我是一个专业,我知道我在做什么,我知道,虽然你不能保证它,我告诉你这个动物变量绝对会成为狗。



由于动物实际上不是狗(它是一种动物,你可以做 Animal animal = new Dog ); 这将是一个狗)VM在运行时抛出异常,因为你违反了这种信任(你告诉编译器一切都会好起来,而不是!)



编译器比只是盲目地接受一切都要聪明些,如果你尝试在不同的继承层次结构中转换对象(例如将Dog转换为字符串),那么编译器会将它抛回你因为它知道永远不可能工作。



因为你本质上只是阻止编译器抱怨,每次你强迫它检查你不会通过在if语句中使用 instanceof 来产生 ClassCastException $ b

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;
    }
}

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?

解决方案

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."

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!)

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.

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天全站免登陆