中級 › ClassCastException の原因と直し方 › パターン5
ClassCastException の原因と直し方
キャストは宣言にすぎず、実体が違えば実行時に落ちます。
1 public class Main { 2 static class Animal {} 3 static class Dog extends Animal {} 4 static class Cat extends Animal {} 5 public static void main(String[] args) { 6 Animal a = new Dog(); 7 Animal c = (______) a; ^ 8 System.out.println(c); 9 } 10 }
Exception in thread "main" java.lang.ClassCastException:
class Main$Dog cannot be cast to class Main$Catexited with code 1
空欄を埋めてビルドを通す
実体はDogなのにCatへキャストしようとしています。実際のインスタンスと違う兄弟クラスへはキャストできません。
次の問題