Get your CodeRanch badge!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting object references. 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 object references." Watch "casting object references." New topic
Author

casting object references.

Ash Gill
Ranch Hand

Joined: Jun 30, 2011
Posts: 71
Hi guys, i have a doubt in object reference casting, in the following code:


from what i understand ##2 should also produce a runtime error, but obviously it isnt. please help me understand the correct logic

thanks and regards
Hama Kamal
Ranch Hand

Joined: May 29, 2011
Posts: 144

d1 = (Dog)a; ##2 this compiles and runs though a is not an istanceOf dog, how is it still being downcast to a Dog


IT GIVES RUN TIME ERROR AS WELL ,,, PLEASE TRY AGAIN!


``Worry does not empty tomorrow of its sorrow; it empties today of its strength.''
Ash Gill
Ranch Hand

Joined: Jun 30, 2011
Posts: 71
Hama Kamal wrote:
d1 = (Dog)a; ##2 this compiles and runs though a is not an istanceOf dog, how is it still being downcast to a Dog


IT GIVES RUN TIME ERROR AS WELL ,,, PLEASE TRY AGAIN!


Apologies, yes it does. i was skipping a line in my original code, which makes all the difference. Sorry for wasting your time.
Hama Kamal
Ranch Hand

Joined: May 29, 2011
Posts: 144

Sorry for wasting your time


You are most welcome my friend, never mind..
Tommy Delson
Ranch Hand

Joined: Apr 13, 2011
Posts: 206
I recommended do a search first for similar topic. See my post and discussion on a similar topic for more info.

http://www.coderanch.com/t/544105/java-programmer-SCJP/certification/downcasting-or-upcasting-ref-variable

You need an "instanceof" test before the downcast to ensure, otherwise, it will throws an exception.

//d1 = (Dog)new Animal(); ##1 this gives a runtime error as Animal is not an instance of Dog

It give a runtime error simply you were creating an anonymous object instead of Animal with statement "new Animal();" on the cast. Change it to "d1 = (Dog)a;" like you did and it will fix the problem.


Here is a recap and hope it help:



OCPJP6-05-11
"Your life is in your hands, to make of it what you choose."
Ash Gill
Ranch Hand

Joined: Jun 30, 2011
Posts: 71
hey thanks Tommy, i understand.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: casting object references.
 
Similar Threads
ClassCast Exception
Reference Variable Casting?
method invocation problem
Seeking Exam Advise
parantheses in explicit casting