ClassCastException

13,097

Solution 1

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.

Solution 2

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".

Solution 3

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.

Share:
13,097
Kalpesh Jain
Author by

Kalpesh Jain

Updated on June 17, 2022

Comments

  • Kalpesh Jain
    Kalpesh Jain almost 2 years

    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;
    
     public void sayhello() {
     System.out.println("class B");
     }
    
    }
    
    public class HelloWorld {
        public static void main(String[] args) throws IOException {
    
     B b = (B) new A();
         System.out.println(b.a);
        }
    }
    

    at compile time it does not give error, but at runtime it displays an error : Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B