Update constructor using method

I have a game app and I want it to update the constructor strength value when I call the levelUp() method.

public Hero(String heroname, double strength, double strength_gain){
    this.heroname = heroname;
    this.hp = (int) (200+20*strength);
    this.strength_gain = strength_gain;
}

public void levelUp(){
    this.strength = strength + strength_gain;
}

But when i do System.out.println(hero.hp); after calling levelUp() it returns the first value.

>Solution :

One way to always get an up-to-date value for a calculation that depends on other variables/inputs is to calculate it on demand (useful for simple calculations, such as the one you have).

EDIT: I realized that you might want to have an hp and a maxHp if your hero can actually lose/gain hp so I edited the example to take that into account.

public class Hero {
    // ...
    public int hp;

    public Hero(String heroname, double strength, double strength_gain){
        this.heroname = heroname;
        this.strength = strength; // <-- don't forget to save the initial strength as well
        this.strength_gain = strength_gain;
        this.hp = getMaxHp();
    }

    public int getMaxHp() {
        return (int) (200 + 20 * strength);
    }

    public void levelUp(){
        strength = strength + strength_gain;
        // decide if leveling up also heals your hero?
        hp = getMaxHp()
    }
    // ...
}

Elsewhere in code you can access both the .hp and the .getMaxHp().

System.out.println(hero.hp);
System.out.println(hero.getHp());

If the calculations would be heavy, then using a boolean as a change flag and lazily recalculating only once per change and only when required would make more sense.

Leave a Reply