File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unable to understand reason for ClassCastException

 
Priyadarshan Kelkar
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please can someone explain why I get a class cast exception



Thanks in advance.
 
Mehmet Gunacti
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ClassCastException
 
Priyadarshan Kelkar
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mehmet !
 
Tommy Delson
Ranch Hand
Posts: 206
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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...
 
Hama Kamal
Ranch Hand
Posts: 144
Java Linux Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic