ClassCastException

后端 未结 4 1856
野趣味
野趣味 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:37

    First do it like this :

      A aClass = new B(); 
    

    Now do your Explicit casting, it will work:

       B b = (B) aClass;
    

    That mean's Explicit casting must need implicit casting. elsewise Explicit casting is not allowed.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-21 00:50

    This happens because the compile-time expression type of new A() is A - which could be a reference to an instance of B, so the cast is allowed.

    At execution time, however, the reference is just to an instance of A - so it fails the cast. An instance of just A isn't an instance of B. The cast only works if the reference really does refer to an instance of B or a subclass.

    0 讨论(0)
  • 2020-12-21 01:00

    B extends A and therefore B can be cast as A. However the reverse is not true. An instance of A cannot be cast as B.

    If you are coming from the Javascript world you may be expecting this to work, but Java does not have "duck typing".

    0 讨论(0)
提交回复
热议问题