i have a Device parent class like this
class Device{
int id;
public Device(int id);
}
and some child devices
class SwitchDevice extends Device{
boolean state;
public SwitchDevice(int id);
boolean getState();
void setState(boolean state);
}
class LightDevice extends SwitchDevice{
int value;
public SwitchDevice(int id);
int getValue();
void setValue(int value);
}
and then i have a Device handler which has a list of Device objects and some methods to retreive device instances from the list
class DeviceHandler {
private List<Device> deviceList;
public DeviceHandler() {
deviceList = new ArrayList<Device>();
}
public Device getById(int devId);
}
i want to know how can i call the childs methods from this list what i mean is something like
Device dev = deviceHandler.getById(0);
boolean state = dev.getState;
i know that in java this is not possible, but maybe you can suggest me how to achieve de result.
i have tried the visitor pattern but in my case is not the right one because it doesn't allow me to return the value.
the only way seems to be adding in the handler class a method for each value of each device like this
boolean getSwitchState(Device dev){
if(dev.instanceOf(SwitchDevice)){
SwitchDevice device = (SwitchDevice)dev;
return device.getState();
}else{
throw new Exception();
}
but it needs a lot of code and is not safe.
I hope you understand what i mean (i'm not so good in english, and not an expert java programmer).