不能在运行时在java中向下转发 [英] Can't not downcast in java at runtime
本文介绍了不能在运行时在java中向下转发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类Animal和一个类Dog如下:
I have a class Animal and a class Dog as following:
class Animal{}
class Dog extend Animal{}
主要类别:
class Test{
public static void main(String[] args){
Animal a= new Animal();
Dog dog = (Dog)a;
}
}
错误显示:
Exception in thread "main" java.lang.ClassCastException: com.example.Animal cannot be cast to com.example.Dog
推荐答案
动物不能是一只狗可以是一只猫或其他像你的情况动物
An animal could not be a dog can be a cat or something else like in your case an Animal
Animal a= new Animal(); // a points in heap to Animal object
Dog dog = (Dog)a; // A dog is an animal but not all animals are dog
对于向下转动你必须这样做
For downcasting you have to do this
Animal a = new Dog();
Dog dog = (Dog)a;
顺便说一下,向下转发很危险你可以拥有这个 RuntimeException
,如果它是用于培训目的,那就没关系。
By the way, downcasting is dangerous you can have this RuntimeException
, if it's for training purpose it's ok.
如果你想避免运行时异常,你可以做这个检查,但它会慢一点。
If you want to avoid runtime exceptions you can do this check but it'll be a little more slower.
Animal a = new Dog();
Dog dog = null;
if(a instanceof Dog){
dog = (Dog)a;
}
这篇关于不能在运行时在java中向下转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文