I read some articles written on \"ClassCastException\", but I couldn\'t get a good idea on that. Is there a good article or what would be a brief explanation?
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 {...}
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.
You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.
If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException For example
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
Above main method will throw below runtime class cast exception
Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable
A very good example that I can give you for classcastException in Java is while using "Collection"
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
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
}