Java protected fields vs public getters

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…

Leave a Comment