簡體   English   中英

Java構造函數的默認參數

[英]default parameter for java constructor

我在名為PlayableFighter的Java類中使用此構造函數

public PlayableFighter(String name, int maxHealthPoints, int blastDamage, int physicalDamage,
        int maxKi, int maxStamina, ArrayList<SuperAttack> superAttacks, ArrayList<UltimateAttack>
        ultimateAttacks)

我想從一個名為Earthling的類中調用它,該類繼承了PlayableFighter,但我沒有superAttacks或UltimateAttacks的值,因此我想將它們設置為默認值,我使用了null,但是有更好的方法嗎?

public Earthling(){
super("Earthling",1250,50,50,4,4,null,null);
}

如果您可以管理PlayableFighter的代碼,我建議添加另一個構造函數,該構造函數將獲取除“ superAttacks”和“ ultimateAttacks”以外的所有參數,這將使用默認參數調用另一個構造函數,如下所示:

public PlayableFighter(String name, int maxHealthPoints, int blastDamage, int physicalDamage, int maxKi, int maxStamina){
this(name, maxHealthPoints, blastDamage, physicalDamage, maxKi, maxStamina, null, null);
}

我不喜歡看到這種方式扔空值。 創建對象時,該對象應100%准備就緒。

我會這樣:

public Earthling() {
    super("Earthling",1250,50,50,4,4,new ArrayList<SuperAttack>(), new ArrayList<UltimateAttack>());
}

您沒有像使用繼承那樣好。 我有一個帶有UltimateAttackSuperAttack子類的Attack接口。

你的名字不好。 誰會知道兩者之間的區別是什么?

為什么必須將“ Earthling”標簽傳遞給Earthling類? 更傻。

您在默認構造函數中傳遞給超級構造函數的所有魔術數字是什么? 更傻。

暫無
暫無

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

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