An instance of a class, in Java, can access private fields of a different instance of its own type, such as in the following listing:
public class Foo {
private int secret;
public void bar(final Foo foo) {
foo.secret = 100;
}
}
What would be the argument for such semantics (when designing a language)?
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.
The private
field is meant to tell other programmers not to mess with it.
Presumably, everyone working in a single class knows what all the variables do. The private
field doesn't hide your own code from you, just from outside.
You can copy/compare values without additional getters and change field without setters. Don't know if in the JVM such simple methods invocations are optimized in any way, but if not, then it produces some overhead.
One may think that keeping such "open" access may lead to some security issues, but when implemeting a class you provide all methods for manipulation of these variables. No one can change them from classes extending this class. As a matter of fact, they are still private - accessible only from your code.
Keep also in mind that logically a class often is destined to do one job. It can be beneficial to share some information and ease access, especially in cases when large amounts of instances are produced. When dealing with cases when more control is needed one can always use package access modifier (which is more "private" in a sense...) or limit instance count with a singleton/factory pattern.
来源:https://stackoverflow.com/questions/30604431/why-can-an-instance-of-a-class-access-private-fields-of-another-instance-of-its