Well, first you have to ask "why have private fields at all?"
Private fields are primarily for encapsulation: a user of a a class shouldn't have to know the internals of that class' implementation. In fact, they shouldn't know, because if they relied on those specifics, then the implementer would be forced to support them or break backwards compatibility. In other words, it protects both the user and designer of the class:
- the user is protected from implementation changes breaking her code
- the designer is protected from having to keep implementation details features unchanged forever
But a class doesn't need to be protected from itself; it doesn't need to worry about the case where one bit of its code changes, but another bit (that uses the first bit) can't change. Backwards compatibility is not a concern, because the class is developed as a single, atomic chunk of code. In other words, neither of the above protections are needed.
Since there's no need to protect the fields, and since it's often necessary to see them (for instance, to compare if two objects are equal), they're visible within the class.
secret
for example, just don't. Coding can't protect you from yourself. – markspace Jun 2 '15 at 19:03private
says only instances ofFoo
can access it. Since you are inFoo
you can access it. – Elliott Frisch Jun 2 '15 at 19:03Foo
class to have access to private fields of differentFoo
instances than referenced bythis
? – Pshemo Jun 2 '15 at 19:06equals(Foo other)
method? – Thilo May 23 '20 at 10:21