Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException

 
verduka fox
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic