不能在运行时在java中向下转发

Vuk*_*uka 1 java inheritance

我有一个类Animal和一个类Dog如下:

  class Animal{}
  class Dog extend Animal{}
Run Code Online (Sandbox Code Playgroud)

而主要课程:

   class Test{
       public static void main(String[] args){
           Animal a= new Animal();
           Dog dog = (Dog)a;
       }
   }
Run Code Online (Sandbox Code Playgroud)

错误显示:

Exception in thread "main" java.lang.ClassCastException: com.example.Animal cannot be cast to com.example.Dog
Run Code Online (Sandbox Code Playgroud)

nac*_*okk 7

动物不能是一只狗可以是一只猫或其他像你的情况一样的动物

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
Run Code Online (Sandbox Code Playgroud)

对于向下转型,你必须这样做

Animal a = new Dog();
Dog dog = (Dog)a;
Run Code Online (Sandbox Code Playgroud)

顺便说一下RuntimeException,如果用于培训目的,那么向下倾斜是危险的,这是可以的.

如果你想避免运行时异常,你可以做这个检查,但它会慢一点.

 Animal a = new Dog();
 Dog dog = null;
  if(a instanceof Dog){
    dog = (Dog)a;
  }
Run Code Online (Sandbox Code Playgroud)