• Post Reply Bookmark Topic Watch Topic
  • New Topic

casting problem with inheritance  RSS feed

 
joe weakers
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there. My question is as follows: I have two classes: StringLayer(located in a package called "gui") and OpenMapLayer(located in a package called "mypackage1") where OpenMapLayer extends StringLayer. Layer is a third class that is the parent of StringLayer(not really relevant here - I think!). When I add layers to an array of objects I declare them as either StringLayer objects or OpenMapLayer objects depending on certain conditions in my database. When I call a certain method in my code I want to take an object of type StringLayer and convert it to an OpenMapLayer object. My code compiles fine but returns a ClassCastException error. My code is as follows:
....
else if(layer instanceof StringLayer)
{
System.out.println(layer.getName()+" turned on");
StringLayer layer1 = (StringLayer) layer; //this is fine
OpenMapLayer oml = (OpenMapLayer)layer1; //this line gives the error
}
....
Surely if OpenMapLayer extends StringLayer then there shouldn't be any problem. Might is be something to do with the packages involved? Can anybody offer me some advise on this please. Thank, Joe
 
Greg T Robertson
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OpenMapLayer extends StringLayer ...

else if(layer instanceof StringLayer)
{
System.out.println(layer.getName()+" turned on");
StringLayer layer1 = (StringLayer) layer; //this is fine
OpenMapLayer oml = (OpenMapLayer)layer1; //this line gives the error
}


This means that layer is an instance of StringLayer hence the cast to StringLayer works fine. However just because it's an instanceof StringLayer it does not mean it's an instance of OpenMapLayer. Every OpenMapLayer will be an instance of StringLayer but not every instance of StringLayer is going to be of type OpenMapLayer.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!