Explanation of ClassCastException in Java
Solution 1:
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.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
Solution 2:
It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
Let's think of a collection of classes.
class A {...}
class B extends A {...}
class C extends A {...}
- You can cast any of these things to Object, because all Java classes inherit from Object.
- You can cast either B or C to A, because they're both "kinds of" A
- You can cast a reference to an A object to B only if the real object is a B.
- You can't cast a B to a C even though they're both A's.