簡體   English   中英

如何在Java中有條件地調用不同的構造函數?

[英]How to call a different constructor conditionally in 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);
    }
}

使用靜態工廠和四個私有構造函數。

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) { 
    ...
  }
  ...
}

是的,@JohanSjöberg說的是什么。

看起來你的例子也是非常做作的。 沒有神奇的答案可以清除這個混亂:)

通常,如果你有這么多構造函數,那么將它們重構為四個獨立的類(一個類應該只負責一種類型的東西)是個好主意。

super必須是構造函數中的第一個語句,因此樣本中的邏輯無效。

正確的方法是在擴展類中創建相同的 4個構造函數。 如果需要驗證邏輯,可以使用例如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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM