【问题标题】:Can't not downcast in java at runtime在运行时不能在java中不沮丧
【发布时间】:2013-07-06 03:07:53
【问题描述】:

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

  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

【问题讨论】:

    标签: java inheritance


    【解决方案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;
      }
    

    【讨论】:

      猜你喜欢
      • 2012-01-18
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多