Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

private/protected access conventions

 
Christopher Fletcher
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34671
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christopher,
A getter and no setter is intended to illustrate "read only." I would go with the getter as it makes a point in the code - that subclasses should not change myHealth. The protected option doesn't do this.
 
Jeff Rummings
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd second what Jeanne said. A good rule of thumb is to keep all data and methods as 'private' as possible, i.e. go with the least visibility you can get away with.

You mentioned that providing a getter in your example is bad OO. I actually think the opposite is true. As for making an extra method call vs direct access, the difference is too insignificant to worry about.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic