Basically, once you make a variable public
, you’re committed and can never go back on this decision. Every future change would change the public interface of your class, which in turn means that every usage of that class needs to be changed. For a public API, this is unthinkable; your library effectively broke backwards compatibility.
Even for privately used classes, this is kind of a big deal.
So when would you ever change the scope of a variable to private
in the future? There are many conceivable reasons for this. The easiest is that your class might need to do something every time the variable’s value is changed (e.g. log the change, or update other variables accordingly). Or you decide later on that the variable isn’t needed at all, and that the value that is requested by the user should be computed on the fly instead.
If you’re directly reading or setting a variable, that’s not possible. Instead, your class needs to force the user to call a getter/setter, by forbidding direct access to the variable and offering appropriate public getter/setter methods in its place.
Because in general you can never foresee such future changes, it has become accepted best practice to make no variable public
. Every variable should be private
(or at least internal).
(There’s one exception: in some cases, final
variables can safely be made public
. For example, enum-like constants are often implemented as public final
variables in Java libraries because they will never change, and no access control is required since they are read-only anyway).