I'm wondering what the convention for handling this type of situation is:
Say I'm designing a simple game where the actors are some subclass of an abstract animat class:
abstract class Animat {
private int myHealth;
... etc
}
class Hoplite extends Animat {
private int spearLength;
... etc
}
class Archer extends Animat {
private int numberOfArrows;
... etc
}
Now, using this model, Archers and Soldiers both have health. This makes sense, but because inheriting classes don't inherit private fields, the only way to allow the classes access to these fields is to either write accessors, or make the fields protected.
Strictly speaking, I'm against straight use of accessors because I don't want to do anything when I access the members, except actually access them. I.E. I wouldn't do something like this in Animat:
public int getMyHealth() {
// some auxiliary accessor method code
return myHealth;
}
I would do this:
public int getMyHealth() {
return myHealth;
}
Since myHealth is going to be accessed so much in the child classes, it would be a pity to always have to access it using a getter (extraneous method calls). Besides, it is bad OO. On the other hand, from what I have read, protected access has some gaping security holes.
What would you guys do in this situation? Is there a nice read-only access level in
java that I missed, or is that very thing a getter?
Thanks!
C Fletcher