Thursday, September 6, 2012

ClassCastException






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 a subclass of Integer, so a ClassCastException will be thrown.

Object i = Integer.valueOf(42);
String s = (String)i;            // ClassCastException thrown here.


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


No comments:

Post a Comment