private
prevents a variable from being accessed directly by another class. You cannot write d.x
to read or write to x
.
If the class chooses to return a reference to x
via a public method, though, that’s it’s own choice to pierce the veil of privacy. Nothing stops A
from allowing x
to be read from a getter or modified from a setter.
In recent years the Java community has recognized the problem with this: namely, if you return a reference to a private mutable object, you open the door for your class’s internal state to be mucked with without its knowledge. To protect against this, it has become good practice to make classes immutable whenever possible.
Indeed, Date
is a perfect example of a poorly-designed mutable class. The java.time
package introduced in Java 8 added a slew of immutable time and date classes to replace Date
. You can now return a private Instant
and not worry about callers being able to change it.
It’s important to point out that immutability comes from how a class is defined. It’s not a language-level feature like private
. Confusingly, final
can be used to make variables immutable, but applying it to a class does not make the class immutable (it makes it unextendable).
1
solved Why can private members in Java be modified from another class?