aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reference Variable Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference Variable Casting " Watch "Reference Variable Casting " New topic
Author

Reference Variable Casting

ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

Hi I have the following piece of code


When i run the code i get the following exception :- Class cast exception at line Line 1 . My question is , Java allows downcasting then why is my code failing to compile ?
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

ragi singh wrote:
My question is , Java allows downcasting then why is my code failing to compile ?

You have misunderstood the down casting. Clue: Down casting for reference variable, not to objects. If you allowed to cast object, then what will be the real logic? You can't cast a object to any other object!


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Minhaj Mehmood
Ranch Hand

Joined: Jan 22, 2007
Posts: 400

Think about the relationships in real life, such as: A child can become parent, but a parent cannot become child again

Test2 is parent and you're forcing it to become child.


Hope this helps

Minhaj


SCJP6 96% | SCWCD5 81% | SCDJWS5 79%
ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

that is to say we cannot downcast objects ?
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

ragi singh wrote:that is to say we cannot downcast objects ?


You can't cast a object! You can make sub class objects with super class reference and make a down cast it to refer with sub class reference again.
ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

ok i got it now thank you .
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

You are Welcome. If we are allowed to cast a object into another, then there is no point of talking polymorphism and other stuff in Java! I think, now you got what does mean by down casting and up casting!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reference Variable Casting