File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes private/protected access conventions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "private/protected access conventions" Watch "private/protected access conventions" New topic

private/protected access conventions

Christopher Fletcher

Joined: May 26, 2007
Posts: 4
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?

C Fletcher
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33119

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Jeff Rummings
Ranch Hand

Joined: Dec 20, 2007
Posts: 42
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.
I agree. Here's the link:
subject: private/protected access conventions
jQuery in Action, 3rd edition