Java protected fields vs public getters

Direct field access is not preferred. Use public or protected setters and getters.

The getter need not be public - if you wan to hide the data from "outsiders", but give the data to subclasses, use protected


Some of Sun's recommendations on controlling access to fields are here. Note that making a field protected exposes it to the package as well, not only to subclasses. Generally, as stated at the link above, fields should be private unless there is a very good reason not to do so.


You should always program against the public API of a class, that is, use the public methods.

The reason is simple. Someday in the future, you or someone else might want to change the implementation. This should always be possible. If you rely on instance variable, you limit yourself.

Also, when accessing the variable, you can not control if that variable is read-only nor can you add checks when this variable is changed.

If you use setters/getters, you can allways add validation, checking etc later on. You can also only provide a getter to make a variable read only.


If there's going to be a public getter anyway, why would you want to expose the field itself more widely than absolutely necessary? That means it's immediately writable by subclasses (unless it's final to start with).

Personally I like all my fields to be private: it provides a cleaner separation between API and implementation. I regard the relationship between a superclass and a subclass as similar to that of a caller and callee - changes to the underlying implementation shouldn't break subclasses any more than they should break callers. The name of a field is an implementation detail which shouldn't impact other classes.

Admittedly my view is occasionally seen as somewhat extreme...

Tags:

Java