簡體   English   中英

Java - 如何根據繼承類的構造函數參數調用不同的super()?

[英]Java - how to call different super() according to inheriting class's constructor argument?

我試圖讓繼承類要求更少的參數,並計算超類的'正確'mising參數。 尋求有關如何執行此操作的幫助,而不使用工廠方法。

這是簡化操作的示例代碼。 Son(int)將根據int的值調用super(int,boolean)。

class Base {
  ...
  public Base (int num, boolean boo2) { ...}
  ...
}

class Son extends Base {
  ...
  public Son (int num) {
    if (num > 17)
       super(num, true);
    else
      super(num , false);
  }
  ...
}

我還考慮過將Base作為接口,但這不允許我強制執行一些參數正確性檢查。

感謝您的幫助。

我不是百分百肯定,但這可以嗎?

class Son extends Base {
  ...
  public Son (int num) {
       super(num, (num>17));
  }
  ...
}

super()調用必須是構造函數中的第一個語句。 在這種情況下,您可以使用:

class Base {
    public Son(int num) {
        super(num, num > 17);
    }
}

如果您需要執行的計算工作比單個表達式長,則可以將其移動到從構造函數調用的靜態方法中:

class Son extends Base {
    public Son(int num) {
        super(num, calcBoo(num));
    }

    private static boolean calcBoo(int num) {
        if (num > 17)
            return true;
        else
            return false;
    }
}

另一種選擇是隱藏構造函數並添加一個靜態工廠方法,這將允許您在調用超級構造函數之前執行任意復雜的工作:

class Son extends Base {
    private Son(int num, boolean boo) {
        super(num, boo);
    }

    public static Son create(int num) {
        boolean boo;
        // ... statements here ... //
        return new Son(num, boo);
    }
}

如果找到其他參數是一個復雜的操作(即,不能簡化為單個表達式),您可以添加一個靜態方法,為您執行此操作並在超級調用中引用它,如下所示:

Class Son extends Base {

  private static boolean getMyBoolean(int num) {
    return num > 17; //or any complex algorithm you need.
  }

  public Son (int num) {
    super(num, getMyBoolean(num));
  }
  ...
}

否則,如果可以使用簡單表達式計算缺少的參數(如您給出的具體示例),只需寫:

Class Son extends Base {
  public Son (int num) {
    super(num, num > 17);
  }
  ...
}

請注意,構造函數調用必須是構造函數中的第一個語句 所以你需要:

public Son (int num) {
   super(num, (num>17));
}

這將做同樣的事情,因為num > 17將被計算為truefalse ,並且它是構造函數中的第一個語句,因此它將被編譯。

查看文檔

調用超類構造函數必須是子類構造函數中的第一行。

構造函數中的第一行必須是對super的調用,否則你就無法擁有它。

為什么不把行為推到Base類? 無論如何,這將是解決這個問題的更好方法。

所以你會有類似的東西:

Son {
  super(num,17); //in base, you have a "break point" parameter
  ....
}

來自JLS§8.8.7

構造函數體的第一個語句可能是對同一個類或直接超類( §8.8.7.1 )的另一個構造函數的顯式調用。

\n ConstructorBody:\n     {ExplicitConstructorInvocation opt BlockStatements opt }\n

super()的調用必須是構造函數的第一個語句 幸運的是,在你的情況下,有一種簡單的方法來濃縮它,正如已經提到的:

public Son(int num) {
    super(num, num > 17);
}

我假設您要求調用super是構造函數中的第一行。

你可以使用像其他答案一樣的簡單布爾表達式,或者你可以推廣解決方案(如果你的例子只是一個例子)並使用一個返回正確值的內聯函數調用。 您也可以查看三元運算符。

暫無
暫無

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

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