[英]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. 然后从该语句开始,从类型参数DeviceTypeToExtend扩展MonitoredDevice类。 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 史蒂夫
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());
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. 不,您不能这样做,因为
MonitoredDevice
类将必须直接从其自己的类型参数扩展,这是不可能的。 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. 取而代之的是,您可以使用类似于
MonitoredDevice<T extends MonitoredDevice<T>>
,就像枚举一样,然后仍然会有超类型的原始类型信息。
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.
如果发布MonitoredDevice和DeviceTypeToExtend的接口可能会有所帮助,因此我们可以更好地了解您希望实现的目标。
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:
您的MonitoredDevice接口可能如下所示:
public interface MonitoredDevice<E> {
E computeFoo();
void doBar();
}
You could also use composition (probably simplest) or a multi-level class hierarchy (not recommended). 您也可以使用组合(可能是最简单的)或多层类层次结构(不推荐)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.