GeeCON Prague 2014*
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
Author

UpCasting and Downcasting

amitesh kumar
Ranch Hand

Joined: Aug 01, 2006
Posts: 50


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


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
RAM KUMAR M.
Greenhorn

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.
 
GeeCON Prague 2014
 
subject: UpCasting and Downcasting