小编典典

无法在运行时在Java中向下转换

java

我有动物课和狗课,如下所示:

  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

阅读 264

收藏
2020-11-23

共1个答案

小编典典

动物不可能是狗,也可能是猫,或者像您这样的动物

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;
  }
2020-11-23