Skip to content
Advertisement

How to access the initial value of an initialized object?

I’m learning java at the moment and I’ve got a question about an object that got initialized and got a variable changed during the program execution.

public class Char {
private String name;
private int skill;
private int defense;
private int life;

private Weapon weapon = Weapon.FISTS;

private Potion potion = null;

So, I want this code to get the initial value of life that got initialized, but how would I access it?

    public boolean isWeak() {
    return life < this.life * 0.25;
}

So, this method is located in the Char class. I’m trying to get it to return a true value when it gets lower than 25%.

    while (hero.isAlive() && monster.isAlive()) {
        if (hero.isWeak() && hero.hasPotion()) {
            hero.sip();
        } else if (monster.isWeak() && monster.hasPotion()){
            monster.sip();
        } else {
            System.out.println(monster.isWeak());
            hero.attack(monster);
            if (monster.isAlive()) {
                monster.attack(hero);
            }
            System.out.println();
        }
    }

Here is the execution program. All the other methods work just fine, but as pointed out, it’ll never return true because it can’t be a quarter of itself. Don’t mind the prints, I’m just testing it.

Advertisement

Answer

To do this, you need to create a second variable that stores the value passed into the constructor:

public class Char {
    private String name;
    private int skill;
    private int defense;
    private int initialLife;
    private int life;
    private Weapon weapon = Weapon.FISTS;
    private Potion potion = null;

    public Char(int initialLife //I am excluding all the other parameters you want to pass in
    ) {
        this.life = initialLife;
        this.initialLife = initialLife;
    }
    public boolean isWeak() {
        return life < this.initialLife * 0.25;
    }

}

As you can see, I store the initial life and I don’t ever modify it. Since I modify the life variable, I can’t use it to keep track of the initial value. Modifying a variable is a destructive process, and Java doesn’t have a way to keep track of the history of variable values (unless you do it yourself as shown above).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement