如何在Java中有条件地调用不同的构造函数?
假设有人为您提供了一个带有以下构造函数的类 Super
:
public class Super
{
public Super();
public Super(int arg);
public Super(String arg);
public Super(int[] arg);
}
假设您想要创建一个子类 Derived
。如何有条件地调用 Super 中的构造函数?
换句话说,让这样的事情发挥作用的“正确”方法是什么?
public class Derived extends Super
{
public Derived(int arg)
{
if (some_condition_1)
super();
else if (some_condition_2)
super("Hi!");
else if (some_condition_3)
super(new int[] { 5 });
else
super(arg);
}
}
Let's say someone gives you a class, Super
, with the following constructors:
public class Super
{
public Super();
public Super(int arg);
public Super(String arg);
public Super(int[] arg);
}
And let's say you want to create a subclass Derived
. How do you conditionally call a constructor in Super
?
In other words, what is the "proper" way to make something like this work?
public class Derived extends Super
{
public Derived(int arg)
{
if (some_condition_1)
super();
else if (some_condition_2)
super("Hi!");
else if (some_condition_3)
super(new int[] { 5 });
else
super(arg);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用静态工厂和四个私有构造函数。
Use static factories, and four private constructors.
是的,@Johan Sjöberg 说的。
看起来你的例子也是高度人为的。没有神奇的答案可以清除这个混乱:)
通常,如果你有这么多构造函数,最好将它们重构为四个单独的类(一个类应该只负责一种类型的事情)。
Yeah, what @Johan Sjöberg said.
Also looks like your example is highly contrived. There's no magical answer which would clear this mess :)
Usually, if you have such a bunch of constructors it would be a good idea to refactor them as four separate classes (a class should be only responsible for one type of thing).
super
必须是构造函数中的第一个语句,因此示例中的逻辑无效。正确的方法是在扩展类中创建相同 4 个构造函数。如果您需要验证逻辑,您可以使用例如
builder
模式。您还可以按照 @davidfrancis 的评论中的建议将所有构造设为私有并提供静态工厂方法。例如,super
must be the first statement in a constructor, hence the logic in your sample is not valid.The proper way is to create the same 4 constructors in your extending class. If you need validation logic you can use e.g., the
builder
pattern. You can also as suggested in the comments by @davidfrancis make all constructs private and supply a static factory method. E.g.,您不能这样做,但您可以从调用您的类的代码中执行此操作:
You can't do that, but you can do this from the code that calls your class:
不能这样做,因为 super 必须是构造函数中的第一个语句。
正确的替代方案是一个构建器类,并在派生类中为超类中的每个构造函数提供一个构造函数。
例如。
Can't be done as such as super must be first statement in a constructor.
The proper alternative is a builder class and to have one constructor in the derived class for each constructor in the super class.
eg.