Search code examples
javainheritanceoopdesign-principles

Specify the supertype of a class upon instantiation/declaration?


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());