ClassCastException

后端 未结 4 1880
野趣味
野趣味 2020-12-21 00:12

i have two classes in java as:

class A {

 int a=10;

 public void sayhello() {
 System.out.println(\"class A\");
 }
}

class B extends A {

 int a=20;

 pub         


        
4条回答
  •  太阳男子
    2020-12-21 00:45

    Once you create the object of a child class you cannot typecast it into a superClass. Just look into the below examples

    Assumptions: Dog is the child class which inherits from Animal(SuperClass)

    Normal Typecast:

    Dog dog = new Dog();
    Animal animal = (Animal) dog;  //works
    

    Wrong Typecast:

    Animal animal = new Animal();
    Dog dog = (Dog) animal;  //Doesn't work throws class cast exception
    

    The below Typecast really works:

    Dog dog = new Dog();
    Animal animal = (Animal) dog;
    dog = (Dog) animal;   //This works
    

    A compiler checks the syntax it's during the run time contents are actually verified

提交回复
热议问题