I have a superclass called “Canvas,” from which I create several subclasses. I want to store instances of those subclasses in a dictionary. So I tried setting up my code as follows:
public class Main {
public static void main(String[] args) throws Exception{
Canvas canvas = new Canvas();
Menu menu = new Menu();
Instructions instructions = new Instructions();
Map<String, Canvas> screens = new HashMap<String, Canvas>();
screens.put("menu", menu);
screens.put("instructions", instructions);
So, being that the things I want to add to the dictionary are all subclasses of my Canvas class, I set up the hashtable to accept that Type. And this works.. for the most part. However, the big problem is that I cannot access any of the subclass’ methods. I can only call methods that exist in the superclass.
If I attempt to do something like,
screens.get("menu").some_func_in_subclass();
The compiler spits out a “Can not find symbol” message.
So, if I have something like this:
SuperClass
|
|
+------------------------------------
| | |
SubClass1 SubClass2 SubClass3
How would I store instances of those subclasses in a HashMap?
That’s the idea of polymorphism – all the sub-classes of
Canvasshare the same methods (from theCanvassuper class) but if you add methods to those classes they are not shared any longer.One way would be to cast your result (assuming you have checked that the value really is a
Menu):But it defeats the purpose of holding everything in a
Map<String, Canvas>in the first place.In the end, either you need
Canvasobjects, and you should not have to call sub-classes methods, or you need something more specific and there probably is a design issue.