Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

casting objects

Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, i got this question from the mock exam page:

What will happen if you attempt to compile and run the following code?

1) Compile and run without error
2) Compile time Exception
3) Runtime Exception

The answer is supposedly 3) cus the guy says that its not allowed to cast down from a higher object to a lower the same question is WHY?
In primitives...cant you cast down from a float to an int? or is it different for objects?

oh and the code tags we have at d they automatically format the code..or i still have to arrange it myself?
Ranch Hand
Posts: 2410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because a Base object is not a Sub object.

You are always allowed to make a cast to a subclass at compile-time.

However, at run-time if the cast is not allowed, you will get a ClassCastException.
Bras cause cancer. And tiny ads:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic