如何在Java中有条件地调用不同的构造函数?

Meh*_*dad 11 java constructor

让我们说有人给你一个类Super,具有以下构造函数:

public class Super
{
    public Super();
    public Super(int arg);
    public Super(String arg);
    public Super(int[] arg);
}
Run Code Online (Sandbox Code Playgroud)

我们假设您要创建一个子类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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Lou*_*man 9

使用静态工厂和四个私有构造函数.

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) { 
    ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)


JHo*_*nti 3

是的,@Johan Sj\xc3\xb6berg 说的。

\n\n

看起来你的例子也是高度人为的。没有神奇的答案可以解决这个混乱:)

\n\n

通常,如果您有这么多构造函数,最好将它们重构为四个单独的类(一个类应该只负责一种类型的事情)。

\n

  • 我在实际代码中遇到了这个问题:为 android 编写向后兼容的代码:“LinearLayout”根据“android.os.Build.VERSION.SDK_INT”的值有不同的构造函数。 (4认同)