我有动物课和狗课,如下所示:
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;
顺便说一句,垂头丧气是危险的,您可以使用它RuntimeException,如果出于培训目的也可以。
RuntimeException
如果要避免运行时异常,可以执行此检查,但是会慢一些。
Animal a = new Dog(); Dog dog = null; if(a instanceof Dog){ dog = (Dog)a; }