ClassCastException in Java with Example

This Java example demonstrates the usage of ClassCastException class with an example.
 
ClassCastException has thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
 
This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.

ClassCastException Class Diagram

From the above class diagram, ClassCastException is a superclass of RunTimeException and Exception class. 

Common Scenarios 

Incorrect Downcasting: Trying to cast a parent class object to one of its child classes. 

Collections without Generics: Using collections without specifying the type (pre-Java 5 style) can lead to runtime casting issues. 

Frameworks and APIs: Misusing certain libraries or APIs that require explicit type casting can also lead to this exception.

Java ClassCastException Example #1

Here is a very simple example, an Integer object cannot be cast to a String object:
public class ClassCastExceptionExample {
    public static void main(String[] args) {
        Object obj = new Integer(100);
        System.out.println((String) obj);
    }
}
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
 at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)

Java ClassCastException Example #2

The next example is more complex and aims to show that an instance of the parent class cannot be cast to an instance of the child class.
package com.javaguides.corejava;

class Animal {

}

class Dog extends Animal {

}

class Lion extends Animal {

}

public class ClassCast {

    public static void main(String[] args) {

        try {
            Animal animalOne = new Dog(); // At runtime the instance is dog
            Dog bruno = (Dog) animalOne; // Downcasting

            Animal animalTwo = new Lion(); // At runtime the instance is animal
            Dog tommy = (Dog) animalTwo; // Downcasting
        } catch (ClassCastException e) {
            System.err.println("ClassCastException caught!");
            e.printStackTrace();
        }

    }

}
Output:
ClassCastException caught!
java.lang.ClassCastException: com.javaguides.corejava.Lion cannot be cast to com.javaguides.corejava.Dog
 at com.javaguides.corejava.ClassCast.main(ClassCast.java:24)

Handling ClassCastException 

Use instanceof: Before casting, check if the object is an instance of the desired class using the instanceof operator. 

Embrace Generics: Generics, introduced in Java 5, allow you to define type-safe classes and methods ensuring type compatibility at compile-time. 

Be Careful with Libraries: When using third-party libraries, always consult the documentation to understand object types and casting expectations. 

Code Reviews: Often, a second set of eyes can catch dubious type-casting that might have been overlooked. 

Best Practices 

  • Keep inheritance hierarchies clear and straightforward, reducing the chances of inadvertent typecasting. 
  • Favor composition over inheritance when designing classes. This approach reduces the overall need for casting and the associated risks. 
  • Whenever you feel the urge to use explicit casting, double-check your design decisions. There's often a better way.

Comments