Search code examples
javainheritancesubclasssuperclass

How to use subclass parameters in superclass method?


I have a superclass called Player, and I have 3 subclasses that are Young Hustler, Student and The Herbalist.

In every subclass I have private parameters money, stashSize and connections.

And I want to create a method in Player class called sellWeed() which removes 1 from stashSize and adds 10 to money, so that I could apply that method to all of the subclasses when calling them in the main method. But how do I get the private parameters from subclasses into the superclass?

I can't declare them in superclass because each subclass has it's own default starting parameters which should progress during the game.


Solution

  • Something like this should work:

    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
      }
    }
    

    The idea is to move the private parameters to the super class. Then you can initialize them by passing the values to the super constructor (super()).