Linda said:
That statement is often seen, but then why does Sun violate that rule
all the time? Their classes are full of public constants, see for
instance java.awt.GridBagConstraints.
What I said does not apply to immutable constants, since they
don't need access control, being constant. Actually, most of them
are just a lazy man's replacement for enumerations, which leads
us to the realization that Sun's programmers aren't neccesarily
the best and brightest: there are a lot of places where the Sun
code is badly designed or just plain crappy in various ways.
The real reason to use getXX and
setXX methods seem to be to be able to use your class as a bean.
So why does the bean specification require get and set methods
instead of public variables?
Because it's more flexible and allows you to do all kinds of things
in the methods beyond getting and setting the value, such as notifying
listeners of the change - something that doesn't only make sense
for JavaBeans.
Especially if I don't intend to make my classes public, so I don't run
the risk of some dumb user modifying the public fields, I see no
practical argument why I should avoid public fields.
The dumb user may well be yourself. Encapsulation is just as much about
protecting you against your own mistakes as it is about others' mistakes.
And it's not just about mistakes, the main point is to keep behaviour
localized. If you ever realize that you need to do something whenever
a certain variable changes, e.g. write a log entry or notify listeners,
then if you used a setter method, you just add a single line of code.
If it is a public field, you have to look all over your code and
add the same line of code everywhere (or change it to a setter method).