• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

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.
 
What a show! What atmosphere! What fun! What a tiny ad!
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic