• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

UpCasting and Downcasting

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
House b = (House)new Building();

Because parent class cannot typecaste to child class
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anyone expalin step by step ?
i didnt get clear Still...
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic