为超级构造函数准备参数
我有一个必须使用参数构造的基类。在子类中,我需要在构造基类之前准备此参数,但在 Java 中,必须在执行其他操作之前调用 super。处理这种情况的最佳方法是什么(参见下面的简单示例)。
class BaseClass {
protected String preparedParam;
public BaseClass(String preparedParam) {
this.param = param;
}
}
class ChildClass {
public ChildClass (Map<String, Object> params) {
// need to work with params and prepare param for super constructor
super(param);
}
}
I have a base class that have to be constructed with parameter. In child class I need to prepare this parameter before constructing base class but in Java super must be called before anything else. What's the best way to handle this situation (see simple example below).
class BaseClass {
protected String preparedParam;
public BaseClass(String preparedParam) {
this.param = param;
}
}
class ChildClass {
public ChildClass (Map<String, Object> params) {
// need to work with params and prepare param for super constructor
super(param);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以创建一个静态方法来执行转换并调用它。
You can create an static method, that does the transformation and call that.
这是一种方法:
Here's one approach:
因为必须准备/初始化的许多参数很简单工厂方法对我来说是更好的解决方案。在我看来,这是更清晰的解决方案。无论如何,谢谢大家的回答。
because of many parameters that have to be prepared/initialized is simple factory method better solution for me. It's little bit clearer solution at my point of view. Anyway thanks all for answers.
我认为罗曼的回答是迄今为止最好的。
如果父类提供了默认构造函数,则可以实例化一个super的对象,然后使用setter方法。
I would rate Roman's answer as the best so far.
If the parent class provides a default constructor, you can instantiate an object of super and then use the setter method.