• 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
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

ClassCastException.

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
why am I getting ClassCastException when I execute my pgm which performs downcasting as show below.
cow = (Cow) animal;
as the naming imply,Cow is a subclass which extends Animal class.
cow and animal are instance vars.
Thanks.
 
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you answered your own question read your question
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi cics
You did kind of answer your own ques but an explanation might not hurt. Think of casting like this
Animal
|
|
Cow
Cow has all the attributes of an animal, however an animal does NOT have all the attributes of cow. Therefor you may legally cast UP the tree, a (Animal)Cow cast is legal because you could call any of the methods in animal on a cow. but low and behold if you try to milk an animal it would'nt know what your talking about..... get it?? You can only legally Cast up the inheritance tree...
 
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can cast down if and only if the object you are casting is an object that you are casting it to:
Animal animal = new Cow();
Cow cow = (Cow)animal;
the above is perfectly legal since animal was a Cow all the time!
but
Animal animal = new Animal();
Cow cow = (Cow)animal;//Run Time Error animal was never a cow

[This message has been edited by Carl Trusiak (edited June 16, 2000).]
 
Hey, check out my mega multi devastator cannon. It's wicked. It makes this tiny ad look weak:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic