I'm working on an inventory program in Java. I have each object in the inventory stored as a relavent class type in a DefaultListModel
and JList
for each location; for example, if I have a video called "Mulan" and a generic thing called "Ball" in a location "Dorm", in the JList
called "Dorm", "Mulan" will be an instance of video
and "Ball" will be an instance of thing
. All the classes are inherited from thing.
I'm trying to do something like this...
Dorm.getSelectedValue().methodInVideoOrThing;
...but when I try it, it says:
error: cannot find symbol
Dorm.getSelectedValue().methodInVideoOrThing();
^
symbol: method methodInVideoOrThing()
location: class Object
Because the DefaultListModel stores each object in a generic object
variable, I'm not able to access the methods for any of the classes I made. I tried this...
class c = Dorm.getSelectedValue().getClass();
c A = (c) Dorm.getSelectedValue();
A.methodInC;
... but it returned the following error:
error: cannot find symbol
c A = (c) Dorm.getSelectedValue();
^
symbol: class c
error: cannot find symbol
c A = (c) Dorm.getSelectedValue();
^
2 errors
symbol: class c
I know I could just cycle through all the classes using isInstanceOf
and downcast on a case by case basis, but that would be quite tedious. Plus, when I do...
System.out.println(Dorm.getSelectedValue().getClass());
...it returns either class video
or class thing
, depending on whether "Ball" or "Mulan" is selected, so I know that java knows what class it is.
So, is there some way I can access the methods of a subclass, when that subclass is stored as a variable of type object, without downcasting? Or is there a way to do this with downcasting and I'm just doing it wrong?