Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading