抽象类构造函数中的抽象方法:设计缺陷?
我有一个抽象类Entity
。每个扩展 Entity
的类都需要一些默认设置和一些可自定义的设置:
public abstract class Entity {
protected Entity() {
// ... default setup
customSetup();
}
protected abstract void customSetup();
// ...
}
我的扩展类 MyEntity
在构造函数中采用一个参数,该参数将在 customSetup()< /code>:
public class MyEntity extends Entity {
private Data data;
public MyEntity(Data d) {
super(); // in here customSetup() is called!
data = d;
}
@Override
protected void customSetup() {
codeDependingOn(data); // will throw NPE: data==null yet!
}
}
正如注释所述,此代码将不起作用。
我可以扔掉 customSetup()
并将所有自定义代码放在 super()
之后,但是使用该抽象方法可以让您更清楚应该放在那里的内容。
我觉得我违反了 OOP 设计的一些规则。做我想做的事的正确方法是什么?
I have an abstract class Entity
. Every class extending Entity
will need some default and some customizable setup:
public abstract class Entity {
protected Entity() {
// ... default setup
customSetup();
}
protected abstract void customSetup();
// ...
}
My extending class MyEntity
takes a parameter in the constructor, that will be used in customSetup()
:
public class MyEntity extends Entity {
private Data data;
public MyEntity(Data d) {
super(); // in here customSetup() is called!
data = d;
}
@Override
protected void customSetup() {
codeDependingOn(data); // will throw NPE: data==null yet!
}
}
As comments state, this code won't work.
I could just throw away customSetup()
and put all the custom code after super()
, but having that abstract method makes clearer what you're supposed to put there.
I feel like I'm violating some rule of OOP design. What's the correct way to do what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用可以从构造函数重写的方法通常是一个坏主意。问题是类还没有完全初始化,当在子类中调用该方法时,可能会带来麻烦。
看看这个问题:构造函数中的可重写方法调用有什么问题? ,它有一个很好的解释。
This is generally a bad idea to call methods which can be overriden from a constructor. The problem is that the class is not yet fully initialized, and when the method is called in a subclass, it may cause trouble.
Take a look at this question: What's wrong with overridable method calls in constructors?, it has a good explanation.