Two Laptop Bag
The moose likes Java in General and the fly likes ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "ClassCastException" Watch "ClassCastException" New topic


verduka fox
Ranch Hand

Joined: Jan 18, 2001
Posts: 178
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 ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24193

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.

[Jess in Action][AskingGoodQuestions]
Timmy Marks
Ranch Hand

Joined: Dec 01, 2003
Posts: 226
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 ]
I agree. Here's the link:
subject: ClassCastException
It's not a secret anymore!