Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

UpCasting and Downcasting

 
amitesh kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
House b = (House)new Building();

Because parent class cannot typecaste to child class
 
RAM KUMAR M.
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone expalin step by step ?
i didnt get clear Still...
 
John Kelty
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic