【问题标题】:default parameter for java constructorjava构造函数的默认参数
【发布时间】:2016-06-05 06:39:00
【问题描述】:

我在一个名为 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);
}

【问题讨论】:

  • 构造函数重载
  • 不,没有更好的方法,除非您创建一个。它们都是 List 类型,因此您可以轻松传递一个空 List。我会更改参数类型以更喜欢界面。

标签: java inheritance constructor polymorphism default


【解决方案1】:

如果您可以管理PlayableFighter 的代码,我建议添加另一个构造函数,该构造函数获取除“superAtttacks”和“ultimateAttacks”之外的所有参数,它们将使用默认参数调用另一个构造函数,如下所示:

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

【讨论】:

    【解决方案2】:

    我不喜欢看到这样乱扔空值。创建对象时,它应该 100% 准备就绪。

    我会这样做:

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

    你没有像你可能的那样使用继承。我会有一个带有子类UltimateAttackSuperAttackAttack 接口。

    你的名字不好。谁知道这两者之间有什么区别?

    为什么必须将“Earthling”标签传递给Earthling 类?更愚蠢。

    你在默认构造函数中传递给超级构造函数的那些神奇数字是什么?更愚蠢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 2010-12-10
      • 2013-06-08
      • 2015-06-26
      • 2015-02-23
      相关资源
      最近更新 更多