Specify the supertype of a class upon instantiation/declaration?
-
18-09-2019 - |
Question
Is it possible to specify the parent of a class when I instantiate/declare that class? For example, can I do something similar to this:
MonitoredDevice<DeviceTypeToExtend> device = null;
And then from that statement, the MonitoredDevice class would extend from the type parameter DeviceTypeToExtend. Now, I know that you can't use type parameters to extend from a superclass, but does anyone know of something similar to achieve this goal of "dynamically" extending from a specific parent.
Thanks,
Steve
Solution
Inheritance is overrated, use composition instead (it's more powerful and flexible):
MonitoredDevice monitored = new MonitoredDevice();
monitor.setTargetDevice(new BaseDevice());
or a decorator pattern:
new MonitoredDeviceDecorator(new BaseDevice());
OTHER TIPS
No, you can't do that because then the MonitoredDevice
class would have to extend directly from its own type parameter, which is not possible. You could instead have something like MonitoredDevice<T extends MonitoredDevice<T>>
, as with Enums, and then there would still be raw type information for the supertype.
You have a lot of options. It may help if you post the interfaces for MonitoredDevice & DeviceTypeToExtend, so we can get a better picture of what you're hoping to achieve.
mhaller's feedback makes sense; you probably don't want to do it all with inheritance.
One possibility: use generics. Your MonitoredDevice interface might look like this:
public interface MonitoredDevice<E> {
E computeFoo();
void doBar();
}
You could also use composition (probably simplest) or a multi-level class hierarchy (not recommended).