Can';在java中,t在运行时不向下转换
我有一个班级动物和一个班级狗,如下所示:Can';在java中,t在运行时不向下转换,java,inheritance,Java,Inheritance,我有一个班级动物和一个班级狗,如下所示: 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"
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
动物不可能是狗,也可以是猫或其他类似动物的东西
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
要想让人失望,你必须这样做
Animal a = new Dog();
Dog dog = (Dog)a;
顺便说一句,向下播放是危险的,您可以使用此运行时异常
,如果是出于培训目的,则可以
如果您想避免运行时异常,可以执行此检查,但速度会慢一点
Animal a = new Dog();
Dog dog = null;
if(a instanceof Dog){
dog = (Dog)a;
}
动物不可能是狗,也可以是猫或其他类似动物的东西
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
要想让人失望,你必须这样做
Animal a = new Dog();
Dog dog = (Dog)a;
顺便说一句,向下播放是危险的,您可以使用此运行时异常
,如果是出于培训目的,则可以
如果您想避免运行时异常,可以执行此检查,但速度会慢一点
Animal a = new Dog();
Dog dog = null;
if(a instanceof Dog){
dog = (Dog)a;
}