| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Why down casting throws ClassCastException?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Why down casting throws ClassCastException?
You cannot assign a You can not just take a parent object and suddenly turn it into a child though. The parent object is not an instance of the subclass. If the actual object holded by the reference is a superclass object, casting it to a subclass reference result in a compile time error.
class SuperClass {
...
}
class SubClass extends SuperClass {
...
}
public class Program {
public static void main(String[] args) {
SuperClass p1 = new SuperClass(); // case 1: actual SuperClass object
SuperClass p2 = new SubClass(); // case 2: SubClass object is referred by a SuperClass reference
SubClass s1 = (SubClass)p1; //run time error
SubClass s2 = (SubClass)p2; //OK
}
}
|