• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Double Casting

 
Duran Harris
Ranch Hand
Posts: 608
Eclipse IDE Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Will this compile?


Does the b reference get casted to A or B type??
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Duran Harris wrote:[/code]
Does the b reference get casted to A or B type??


First get casting to A then B. So in the end it is get casting to B. Why? What did you think about this? Please let us know.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Duran,

(B)(A) b;
First casts a B type reference to the A reference type, obtaining an A type reference. This is guaranteed to both compile and run without error (upcasting.) Second, cast the A type reference to the B reference type. This is guaranteed to compile, but may or may not throw an exception based on the actual type of the object (downcasting.) Since the type of the object referred to by b is B, in this case the casting works, and you end up with the same reference you started with (b, a reference of type B pointing to an object of type B.)
 
Duran Harris
Ranch Hand
Posts: 608
Eclipse IDE Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok thanks..

I got the idea from Devaka's exam lab.I was just unsure of whether the casts run from right to left
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic