I am having trouble remembering how to properly cast objects. I have an object that is a child of another class. Then I add the parent objects to a Vector. When I retrieve the objects from the Vector, I want to cast it to the child object. When I do so, I'm receiving a class cast exception. Please see the code below. I appreciate clarification on this point.
Your clarification is greatly appreciated! [ January 15, 2004: Message edited by: verduka fox ]
You can't use a cast to convert an object to a type that it doesn't have. The Vector contains A objects, and you can't use a cast to convert them to B objects. If you need B objects in the Vector, then you need to create and add B objects. Otherwise, the cast before "get()" must be to A, not to B. You can use a cast to convert a B into an A, since a B is an A; so if the Vector did contain B objects, then the cast could be either to A or B; both would work.
Correct. Consider this: A woman is a person (usually ) therefore a woman can do everything a person can. But a person is not necessarily a woman, therefore you can not expect a normal person to be able to do everything a woman can do.
is probably not a good idea unless you are sure that (a instanceof Woman) You can always cast up the hierarchy, but you should probably check before downcasting. [ January 15, 2004: Message edited by: Timmy Marks ]