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 ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • 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 jhcq.net 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 object..in the same hierarchy...my 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 ranch..do they automatically format the code..or i still have to arrange it myself?
thankx
 
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
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic