This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Developer Career Masterplan: Build your path to senior level and beyond with practical insights from industry experts and have Heather VanCura and Bruno Souza on-line!
See this thread for details.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Liutauras Vilda
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Piet Souris

Unable to understand reason for ClassCastException

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please can someone explain why I get a class cast exception



Thanks in advance.
 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 :

 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ClassCastException
 
Priyadarshan Kelkar
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Mehmet !
 
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
https://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...
 
Ranch Hand
Posts: 144
Netbeans IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic