• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

casting problem with inheritance

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic