Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
Why down casting throws ClassCastException?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: Why down casting throws ClassCastException?

Why down casting throws ClassCastException?

You cannot assign a superclass reference variable to a subclass reference without a cast of the subclass type. Examples can find in When is an explicit object reference casting is required?. The compiler is happy when you explict cast the superclass reference to subclass reference, but the compiler does not care what the actual object holded by the reference. Does it actually have a superclass object, or just a superclass reference holding a subclass object? No answer from compile time but it has to answer this quesiton.

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
  }
}

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help