ClassCastException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. — Official statement.

A guaranteed ClassCastException 😀

 

 

ClassCastException is a runtime exception belongs to java.lang package.

 

Object in = 10;

String s = (String)in;

 

The above code compiles but while running you get a ClassCastException with a message

java.lang.Integer cannot be cast to java.lang.String

ClassCastException  has two constructors, one default and another one which takes a String as an argument which is the specified detail message.

ClassCastException has methods inherited from Throwable and Object classes.

 

Consider a class hierarchy of Animals below :

 

class Animal{}

class Parrot extends Animal{}

class Dog extends Animal{}

class GermanShepherd extends Dog{}

 

Now create an object of Animal :

 

Animal a = new Animal();

Dog d = (Dog)a; // Here casting is required. Otherwise it gives a compile time error saying that Type mismatch: cannot convert from Animal to Dog.

But while running the above code it throws a ClassCastException with the message that java.lang.ClassCastException: Animal cannot be cast to Dog

 

The problem with the above code is that a is an object variable of type Animal and referring Animal. It is not referring Dog, but we casted it to Dog.

But if the code was like below, it would have worked perfectly fine.

Animal a = new Dog(); // This is correct and called implicit casting or upcasting.

 

Dog d = (Dog)a;  // This is correct and called explicit casting or downcasting.

Here a is an object variable of type Animal referring Dog. So this casting is correct.

 

But the below code will throw a ClassCastException with a message Dog cannot be cast to GermanShepherd:

Animal a = new Dog();

Dog d = (GermanShepherd)a;

 

Conclusion :

So ClassCastException is thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

Using Java’s exception handling we can deal with the casting problem. Or we may also use the instanceof keyword to avoid incorrect casting.

 

Saju Pappachen

About the author: Saju Pappachen is the Chief Consultant of jThread IT Training & Consultancy. He has more than 20 years of experience in Java technology.

He can be reached at saju@jthread.com

11 thoughts on “ClassCastException

Leave a Reply

Your email address will not be published. Required fields are marked *