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 UpCasting and Downcasting 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 "UpCasting and Downcasting" Watch "UpCasting and Downcasting" New topic

UpCasting and Downcasting

amitesh kumar
Ranch Hand

Joined: Aug 01, 2006
Posts: 50

This code runs and prints
Exception in thread "main" java.lang.ClassCastException: Building
at Terrace.<init>(
at Terrace.main(

Please explain why it throws ClassCastException.
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
House class is a child of Building class. But Building class is not a child of House class. You created an instance of Building class.

Building b = (Building)new House();
House h = (House)b; // no compiler error.
[ August 08, 2006: Message edited by: wise owen ]
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580
House b = (House)new Building();

Because parent class cannot typecaste to child class

Joined: Dec 19, 2005
Posts: 10
Can anyone expalin step by step ?
i didnt get clear Still...
John Kelty
Ranch Hand

Joined: Aug 08, 2006
Posts: 33
The first Building gets printed out in the Terrace constructor, which relies on base class Building's constructor.

The second Building gets printed out in the constructor for b.

Next, the compiler takes this new Buliding and tries to convert it to a House as part of the cast attempt. That fails, because b's run time dynamic type is Building, which cannot be cast to the more specific type House.

By contrast, House b = (House) new Terrace();

would work, because in that case b's runtime type is Terrace, so the cast would be to a more generic type.
I agree. Here's the link:
subject: UpCasting and Downcasting
It's not a secret anymore!