如何在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); } }
是的,@JohanSjöberg说的是什么。
看起来你的例子也是高度做作的。 没有神奇的答案可以清除这个混乱:)
通常,如果你有这么多构造函数,那么将它们重构为四个独立的类(一个类应该只负责一种类型的东西)是个好主意。
使用静态工厂和四个私有构造函数。
class Foo { public static Foo makeFoo(arguments) { if (whatever) { return new Foo(args1); } else if (something else) { return new Foo(args2); } etc... } private Foo(constructor1) { ... } ... }
super
必须是构造函数中的第一个语句,因此样本中的逻辑无效。
正确的方法是在扩展类中创建相同的 4个构造函数。 如果需要validation逻辑,可以使用例如builder
模式。 您也可以按照@davidfrancis的评论中的建议,将所有构造设为私有,并提供静态工厂方法。 例如,
public static Derived newInstance(int arg) { if (some condition) { return new Derived(arg); } // etc }
你不能那样做,但你可以从调用你的类的代码中做到这一点:
if (some_condition_1) new Super(); else if (some_condition_2) new Super("Hi!"); else if (some_condition_3) new Super(new int[] { 5 }); else new Super(arg);
不能像超级必须在构造函数中的第一个语句那样完成。
正确的替代方法是构建器类,并且在超类中的每个构造函数的派生类中都有一个构造函数。
例如。
Derived d = new DerivedBuilder().setArg(1).createInstance();
public class DerivedBuilder { private int arg; // constructor, getters and setters for all needed parameters public Derived createInstance() { // use appropriate constructor based on parameters // calling additional setters if need be } }