jQuery in Action, 3rd edition
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting " Watch "Casting " New topic


Sully Sylvester

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?

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.

Sully Sylvester

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

Joined: Feb 05, 2001
Posts: 17276

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.


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Carol Enderlin
Ranch Hand

Joined: Oct 10, 2000
Posts: 1364

���� Huh

I agree. Here's the link: http://aspose.com/file-tools
subject: Casting
It's not a secret anymore!