Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting object references.

 
Ash Gill
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 144
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Ash Gill
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 144
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for wasting your time


You are most welcome my friend, never mind..
 
Tommy Delson
Ranch Hand
Posts: 206
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Ash Gill
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey thanks Tommy, i understand.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic