This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unable to understand reason for ClassCastException

 
Priyadarshan Kelkar
Ranch Hand
Posts: 31
  • 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
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ClassCastException
 
Priyadarshan Kelkar
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mehmet !
 
Tommy Delson
Ranch Hand
Posts: 206
  • 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
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic