Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassCastException

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

like image 375
Kalpesh Jain Avatar asked Jun 22 '10 11:06

Kalpesh Jain


People also ask

What is a ClassCastException?

Introduction. ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

What is ClassCastException in Java with example?

Straight from the API Specifications for the ClassCastException : Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. So, for example, when one tries to cast an Integer to a String , String is not an subclass of Integer , so a ClassCastException will be thrown.

When should we throw a ClassCastException?

ClassCast Exception is thrown when we try to cast an object of the parent class to the child class object. However, it can also be thrown when we try to convert the objects of two individual classes that don't have any relationship between them.


1 Answers

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.

like image 52
Jon Skeet Avatar answered Sep 30 '22 08:09

Jon Skeet