动物不可能是狗,也可能是猫,或者像您这样的动物
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
,如果出于培训目的也可以。
如果要避免运行时异常,可以执行此检查,但是会慢一些。
Animal a = new Dog();
Dog dog = null;
if(a instanceof Dog){
dog = (Dog)a;
}