• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Casting a supertype to a subtype

 
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic