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 Unable to understand reason for ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Unable to understand reason for ClassCastException" Watch "Unable to understand reason for ClassCastException" New topic
Author

Unable to understand reason for ClassCastException

Priyadarshan Kelkar
Ranch Hand

Joined: Apr 04, 2007
Posts: 31
Please can someone explain why I get a class cast exception



Thanks in advance.
Mehmet Gunacti
Ranch Hand

Joined: Oct 26, 2004
Posts: 34
Hi,

because at runtime "a" refers to an "Animal" object, which you can't cast to a Horse.

This one would work :

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

ClassCastException
Priyadarshan Kelkar
Ranch Hand

Joined: Apr 04, 2007
Posts: 31
Thanks Mehmet !
Tommy Delson
Ranch Hand

Joined: Apr 13, 2011
Posts: 206

You need an "instanceof" test before the downcast to ensure, otherwise, it will throws an exception.

See my post and discussion on a similar topic for more info.
http://www.coderanch.com/t/544105/java-programmer-SCJP/certification/downcasting-or-upcasting-ref-variable

Reread K & B on "Reference Variable Casting (Objective 5.2)" Chapter 2 page 116 for more insight and test the new code to clear your doubt.

Hope it help...


OCPJP6-05-11
"Your life is in your hands, to make of it what you choose."
Hama Kamal
Ranch Hand

Joined: May 29, 2011
Posts: 144

Priyadarshan Kelkar wrote:Please can someone explain why I get a class cast exception



Thanks in advance.

because a is not an instance of Horse ...in order to downcast it should have been upcasted before ,, like


``Worry does not empty tomorrow of its sorrow; it empties today of its strength.''
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Unable to understand reason for ClassCastException