wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting " Watch "Casting " New topic
Author

Casting

Sully Sylvester
Greenhorn

Joined: Jan 05, 2005
Posts: 6
Hi ,
when you have class X and Y and Y extends X.

So assuming i have the following correct.

X x = new X(); (1)
Y y = new Y(); (2)

x = y; (3)
y = (Y)x; (4)

But if you remove the line at (3) line (4) will fail at runtime. My question is why is line (3) neccessary for line (4) to work at runtime and what difference does it make?

Cheers.
David Ulicny
Ranch Hand

Joined: Aug 04, 2004
Posts: 724
y is a child of x.
You can't cast parent to child, because parent knows nothing about his children.


SCJP<br />SCWCD <br />ICSD(286)<br />MCP 70-216
Sumit Deshpande
Ranch Hand

Joined: Jan 10, 2005
Posts: 38

X x = new X(); (1)
Y y = new Y(); (2)

x = y; (3)
y = (Y)x; (4)


At line 3, you are telling x to refer an object of Y at runtime. So, you can "get the object back" from x at line 4. But if you remove line 3, then x is pointing to an Object of X (which has no knowledge about Y). So obviously you cant ask x something which it doesnt know about.
Hope this helps.

-Sumit.
Sully Sylvester
Greenhorn

Joined: Jan 05, 2005
Posts: 6
Yeah that clears it up .
Thanks
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

What do you think? Should Johnny Depp have been casted as Willy Wonka?

Oh, sorry I though this question was about movie casting.

Sorry, go back to your studying and ignore me.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Carol Enderlin
drifter
Ranch Hand

Joined: Oct 10, 2000
Posts: 1364
Mark,

���� Huh

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting
 
Similar Threads
doubt in string question in Kathy Sierras SCJP book
Sun's mock question 4.
int and double variables
Need Help With For Loops
Function not returning values.