I read some articles written on "ClassCastException" but I couldn't get a good idea on that. Can someone direct me to a good article or explain it briefly.
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.
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.
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // no problem, the type animal can be casted to a dog, because its a dog
Cat c = (Dog) a; // raises class cast exception, you cant cast a dog to a cat
You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
Object -> Animal -> Dog
You might have a method called:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.
In later versions of Java you do get a compiler warning unless you do:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}