• 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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).]
 
That's my roommate. He's kinda weird, but he always pays his half of the rent. And he gave me this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic