What are the alternatives to public fields?
- by James
I am programming a game in java, and as the question title suggestions i am using public fields in my classes. (for the time being)
From what i have seen public fields are bad and i have some understanding why. (but if someone could clarify why you should not use them, that would be appreciated)
The thing is that also from what i have seen, (and it seems logical) is that using private fields, but using getters and setters to access them is also not good as it defeats the point of using private fields in the first place.
So, my question is, what are the alternatives? or do i really have to use private fields with getters and setters?
For reference here is one of my classes, and some of its methods.
I will elaborate more if needs be.
//The player's fields.
public double health;
public String name;
public double goldCount;
public double maxWeight;
public double currentWeight;
public double maxBackPckSlts;
public double usedBackPckSlts; // The current back pack slots in use
public double maxHealth; // Maximum amount of health
public ArrayList<String> backPack = new ArrayList<String>();
//This method happens when ever the player dynamically takes damage(i.e. when it is not scripted for the player to take damage.
//Parameters will be added to make it dynamic so the player can take any spread of damage.
public void beDamaged(double damage)
{
this.health -= damage;
if (this.health < 0)
{
this.health = 0;
}
}
public void gainHealth(double gainedHp)
{
this.health += gainedHp;
if (this.health > this.maxHealth)
{
this.health = this.maxHealth;
}
}