GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting a supertype to a subtype Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting a supertype to a subtype" Watch "Casting a supertype to a subtype" New topic
Author

Casting a supertype to a subtype

Santiago Bravo
Ranch Hand

Joined: Jul 25, 2008
Posts: 226
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


Santiago
My Path to SCJP Certification My Path to SCWCD Certification
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Casting a supertype to a subtype