aspose file tools*
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: 24166
    
  30

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]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting a supertype to a subtype
 
Similar Threads
Inner Class Doubt
casting
doubt in casting
Another examLab casting question
Devaka's Practice Exam1