I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at
I think an idiomatic, object oriented way of doing this is to have a setHealth
on the Character
class. The implementation of that method will look like this:
public void setHealth(int newValue) {
health = Math.max(0, Math.min(100, newValue))
}
This prevents the health from going below 0 or higher than 100, regardless of what you set it to.
Your getHealed()
implementation can just be this:
public void getHealed() {
setHealth(getHealth() + 15);
}
Whether it makes sense for the Character
to have-a getHealed()
method is an exercise left up to the reader :)