File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Unable to run the following program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Unable to run the following program" Watch "Unable to run the following program" New topic

Unable to run the following program

Phanikanth Munukutla

Joined: Aug 22, 2006
Posts: 3
class Super
System.out.println("Constructor for Super class");


public class Sub extends Super
System.out.println("Constructor for Sub class");
public static void main(String[] args)
Sub subObj=(Sub)new Super();

The above program( is compiling but while running it is giving ClassCastException.. Why???
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
An instance of Super class is not an instance of its subclass Sub. You can not cast it to Sub.
[ August 25, 2006: Message edited by: wise owen ]
Vaibhav Chauhan
Ranch Hand

Joined: Aug 16, 2006
Posts: 115
As far as compilation is concerned, compiler doesn't know anything about
'new Super()' only JVM can know which object is being created. Compiler doesn't have any problem because you are downcasting 'something' to 'Sub' and assigning the value to 'Sub' reference which is perfectly acceptable for compiler but when it comes to JVM (at runtime) it complains that

"I can't downcast Super "object" (not reference) to another class (even to its subclass)."

downcasting in object reference is acceptable in following case:

Super superReference= new Sub();
Sub subReference=(Sub) superReference;

because here we are downcasting super class reference (which refer to sub class object) to sub class one.
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3632
Good explanation, Vaibhav.
When you put an explicit cast Sub subObj=(Sub)new Super();, you are telling the compiler to ignore the type of the reference and that you are make the compiler believe that at runtime the reference will point to the correct object.

However, in your case, at runtime the reference is not pointing to an object of class Sub (or its subclass). So the JVM throws the exception.

Note: You can think of this statement: Sub subObj=(Sub)new Super();
as :
Super tempReference = new Super();
Sub subObj=(Sub)tempReference;

Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
Vaibhav Chauhan
Ranch Hand

Joined: Aug 16, 2006
Posts: 115
thanks paul.
I agree. Here's the link:
subject: Unable to run the following program
It's not a secret anymore!