[Solved] ClassCastException :A cannot be cast to B : Example

java.lang.ClassCastException is RuntimeException and Unchecked Exception which throws when code has attempted to cast an object to a subclass or class of which it is not an instance.

How to Fix ClassCastException ?

  • Always careful when try to cast an object of a class into another class. Make sure that new  type class belongs to one of its parent classes.
  • Use Generics to prevent ClassCastException because Generics provide compile time checks to develop type-safe applications so that issue identified on compile time.

Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.

Example :
Below are two example of ClassCastException where type casting an objet to different type which is not sub class of object class.

Example 1: Here first converting Integer Object to Object class which is parent class of all classes and then after type casting object of Object class to String Object. Which not compatible with Integer class and not sub class of Integer that’s why throwing ClassCastException.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ClassCastExceptionExample {

	public static void main(String[] args) {
		/**
		 * when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
	 */
		try
		{
		Object object= new Integer(10);
		System.out.println((String)object);
		}
		catch(ClassCastException ex)
		{
			ex.printStackTrace();
		}
	}

}

Example 2:
Here we  are trying to type cast an object of class A into an object of class B, and they aren’t compatible, we will get a class cast exception.

Let’s think of a collection of classes from below example

class A {}
class B extends A {…}
class C extends A {…}
We can cast any of these things to Object, because all Java classes inherit from Object.
We can cast either B or C to A, because they’re both “kinds of” A
We can cast a reference to an A object to B only if the real object is a B.
We can’t cast a B to a C even though they’re both A’s on that point will throw type cast exception.

public class A
{
}
public class B extends A
{
}
public class C extends A
{
}

package example;

public class ClassCastExceptionExample {

	public static void main(String[] args) {		

		try {
         A a=new A();
         A b=new B();
         A c=new C();

         B d=(B)b;
         B e=(B)c;// Exception on that point

		} catch (ClassCastException ex) {
			ex.printStackTrace();
		}
	}

}

Output:

java.lang.ClassCastException: example.C cannot be cast to example.B
	at example.ClassCastExceptionExample.main(ClassCastExceptionExample.java:27)
Advertisements