File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Double Casting 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 "Double Casting" Watch "Double Casting" New topic
Author

Double Casting

Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

Will this compile?


Does the b reference get casted to A or B type??


===>SCJP 1.5(72%)<===
==>SCWCD1.5(76%)<===
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
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.


SCJP 6
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
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.)


All code in my posts, unless a source is explicitly mentioned, is my own.
Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

Ok thanks..

I got the idea from Devaka's exam lab.I was just unsure of whether the casts run from right to left
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Double Casting