Above the first print statement I understand that I create a new "box" called player where I set the value of health to 50. (Ignoring Bert and knife). So the value of health because it is between 0-100 changes to 50. Above the second print statement, I use the keyword "new" so then I create a new "box" also called player and "override" the first player "box" and try to pass the health value of 200 but 200 is not between 0-100 so then the default value is set to 100. What I am trying to achieve without using a setter method in my PlayerNoLeaks class is to "be in the same box" so the value I first pass is 50 so health = 50, then try to pass 200 but can't have a value out of 0-100 so the value remains 50. If I take out the default value of 100 in PlayerNoLeaks then the value of 0 prints, so I am betting something is wrong with me using the "new" keyword again in the main class.
Hopefully this makes sense.
Thanks!
public class Main {
public static void main(String[] args) {
PlayerNoLeaks player = new PlayerNoLeaks("Bert", 50, "Knife");
System.out.println("Initial health is " + player.getHealth()); //prints 50
player = new PlayerNoLeaks("Alma", 200, "Sword"); //prints 100
System.out.println(player.getHealth());
}
}
public class PlayerNoLeaks {
private String name;
private int health = 100; //default value
private String weapon;
public PlayerNoLeaks(String name, int health, String weapon) {
this.name = name;
if(health > 0 && health <= 100) {
this.health = health;
}
this.weapon = weapon;
}
public void loseHealth(int damage) {
this.health -= damage;
if(this.health <= 0) {
System.out.println("Player knocked out!");
}
}
public int getHealth() {
return health;
}
}