• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Double Casting

 
Ranch Hand
Posts: 608
Eclipse IDE Spring Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Will this compile?


Does the b reference get casted to A or B type??
 
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Today's lesson is that you can't wear a jetpack AND a cape. I should have read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic