• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting a supertype to a subtype

 
Santiago Bravo
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Question taked from Devaka's exam simulator:




The answer is that the code compiles fine.

Why does line 8 not give a runtime exception? Is it due to the reference 'b' acually referring to a C object?

If I change line 7 to


this will give a runtime exception - ClassCastException.



Thanks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Santiago Bravo:

Why does line 8 not give a runtime exception? Is it due to the reference 'b' acually referring to a C object?


Look at line 6: 'b' actually holds a 'D' object!

If b contained a C, then this would indeed throw an exception.

A cast never changes the class of an object. You can never cast an object to a type that it does not have. The only time you can cast a supertype to a subtype and have it work properly is if the superclass reference is actually referring to an instance of that particular subtype.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic