如何在超类方法中使用子类参数?

时间:2017-06-07 23:00:01

标签: java inheritance subclass superclass

我有一个名为Player的超类,我有3个子类Young HustlerStudentThe Herbalist

在每个子类中,我都有私有参数moneystashSizeconnections

我想在名为Player的{​​{1}}类中创建一个方法,该方法从sellWeed()删除1并将{10}加到stashSize,以便我可以将该方法应用于在main方法中调用它们时的所有子类。但是如何从子类中获取私有参数到超类?

我无法在超类中声明它们,因为每个子类都有自己的默认启动参数,这些参数应该在游戏中进行。

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

class Player {
  protected int money;
  protected int stashSize;
  // and the connections parameter too...
  public Player(int money, int stashSize) {
    this.money = money;
    this.stashSize = stashSize;
  }
  public void sellWeed() {
    // work with money and stashSize here
  }
}

class Student extends Player {
  public Student() {
    super(0, 10); // no money and stashSize 10 for student
  }
}

这个想法是将私有参数移动到超类。然后,您可以通过将值传递给超级构造函数(super())来初始化它们。

相关问题