1

次のように、動物クラスと犬クラスがあります。

  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
4

1 に答える 1

8

動物は犬になることはできませんでした猫またはあなたの場合の動物のような何かになることができます

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でもいいので、トレーニング目的ならOKです。

実行時例外を回避したい場合は、このチェックを行うことができますが、少し遅くなります。

 Animal a = new Dog();
 Dog dog = null;
  if(a instanceof Dog){
    dog = (Dog)a;
  }
于 2013-07-06T03:08:23.527 に答える