使用这两个默认构造函数之间的区别?

时间:2016-04-04 05:04:55

标签: java constructor default-constructor

我能够通过我的代码传递一个秘密测试,它基本上测试了具有特定输入和预期输出的代码。我一直得到一个断言错误,其中说明了预期的< 1>。但是:< 0>直到我改变了代码:

public Gunner(){
    this.gunpower = 1;
    this.GunnerStrength = 1;
    this.name = "Default Gunner";
}

public Gunner() {
    this("Default Gunner", 1, 1);
}

为了进一步说明并给出参考点,以下是上述代码之前的代码:

package ship;

public class Gunner {
    private String name;
    private int gunpower;
    private int GunnerStrength;
    private int maxGupower;
    private int maxGunnerStrength;
    private int currentGunpower;
    private int currentGunnerStrength;

    public Gunner(String l_name, int l_gunpower, int l_GunnerStrength) {
        this.name = l_name;
        this.currentGunpower = maxGunpower = l_gunpower;
        this.currentGunnerstrength = maxGunnerStrength = l_GunnerStrength;
    }

    public Gunner(Gunner other) {
        this.name = new String(other.name);
        this.gunpower = new Integer(other.gunpower);    
        this.GunnerStrength = new Integer(other.GunnerStrength); 
        this.maxGunpower = new Integer(other.maxGunpower); 
        this.maxGunnerStrength = new Integer(other.maxGunnerStrength); 
        this.currentGunpower = new Integer(other.currentGunpower);                                              
        this.currentGunnerStrength = new Integer(other.currentGunnerStrength); 
    }
}

如果有人可以解释上面两个代码之间的差异,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

你原来的Gunner()构造函数试图复制 Gunner(String,int,int)构造函数的逻辑,虽然显然(因为你已经通过了“秘密测试”),它由于填写了不同的字段,因此无法正确执行此操作:它已初始化gunpowerGunnerStrengthname;但另一个构造函数初始化namecurrentGunpowermaxGunpowercurrentGunnerStrengthmaxGunnerStrength。那是一组完全不同的领域。

您修订后的Gunner()构造函数重用 Gunner(String,int,int)构造函数的逻辑,而不是尝试复制它。因此它填补了Gunner(String,int,int)填写的字段。据推测,测试期望填写这些字段。

一般来说,复制逻辑是一个坏主意,因为不可避免的事情随着时间而变化,所以除非有相反的令人信服的论据,否则重用而不是重复逻辑是要走的路。

重新编辑:

  

我一直收到一个断言错误,其中说明了预期的< 1>。但是:< 0>

int字段的默认值为0,因此,如果您未初始化或为该字段指定其他值,则其值为0。因此,大概是单元测试检查原始Gunner()未填写的其中一个字段的值(currentGunpowermaxGunpowercurrentGunnerStrength或{{1} })但您的新maxGunnerStrength 填写(通过Gunner())。

旁注:

  

使用这两个默认构造函数之间的区别?

代码中没有默认构造函数。如果您没有为类定义任何构造函数,则编译器将提供default constructor。由于定义了类的构造函数,因此没有默认的构造函数。

您的Gunner(String,int,int)构造函数是一个没有形式参数的构造函数,有时称为零参数构造函数零参数构造函数 no-arg(s)构造函数(Java使用“参数”而不是“参数”来引用传递给方法和构造函数的东西,但它们通常也被非正式地称为“参数”,因此“args” )。

相关问题