子类构造函数具有不同的值

huangapple go评论56阅读模式
英文:

Subclass constructor with different values

问题

我有一个父类Hammer,然后是他的子类Mjolnir。我想将Mjolnir的remainingUsage设置为4。我通过在Hammer类中创建一个名为setUsage的方法,然后在Mjolnir构造函数中使用它来实现这一点。是否有更简单的方法在不使用setUsage方法的情况下实现它?

public class Hammer extends AbstractActor {
    private int remainingUsage;
    private Animation image;

    public Hammer() {
        this.remainingUsage = 1;
        image = new Animation("sprites/hammer.png");
        setAnimation(image);
    }
}

public class Mjolnir extends Hammer {
    Mjolnir() {
        super();
        this.setUsage(4);
    }
}
英文:

I have parent class Hammer and then his child class Mjolnir. I want to set the remainingUsage for Mjolnir to 4. I managed to do it by creating method in Hammer classs called setUsage and then use it in Mjolnir constructor. Is it possible to do it in more easy way without that setUsage method?

public class Hammer extends AbstractActor {
private int remainingUsage;
private Animation image;

public Hammer() {
    this.remainingUsage = 1;
    image = new Animation("sprites/hammer.png");
    setAnimation(image);
}
}
public class Mjolnir extends Hammer {
    Mjolnir(){
        super();
        this.setUsage(4);
    }
}

答案1

得分: 1

你可以这样做:

...

private int remainingUsages;

public Hammer() { this(1); }
public Hammer(int remainingUsages) { this.remainingUsages = remainingUsages; }

然后在你的子类中只需调用 super(4)。在构造函数内调用其他方法不是良好的做法。

英文:

You can do something like this:

...

private remainingUsages;

public Hammer() { this(1); }
public Hammer(int remainingUsages) { this.remainingUsages = remainingUsages; }

And then just call super(4) from your subclass. Calling other methods within your constructor is not good practice.

huangapple
  • 本文由 发表于 2020年10月22日 15:04:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64476947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定