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.
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...
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).]