java - Why can an instance of a class access private fields of another instance of its own type? -
an instance of class, in java, can access private fields of different instance of own type, such in following listing:
public class foo { private int secret; public void bar(final foo foo) { foo.secret = 100; } }
what argument such semantics (when designing language)?
well, first have ask "why have private fields @ all?"
private fields encapsulation: user of a class shouldn't have know internals of class' implementation. in fact, shouldn't know, because if relied on specifics, implementer forced support them or break backwards compatibility. in other words, protects both user , designer of class:
- the user protected implementation changes breaking code
- the designer protected having keep implementation details features unchanged forever
but class doesn't need protected itself; doesn't need worry case 1 bit of code changes, bit (that uses first bit) can't change. backwards compatibility not concern, because class developed single, atomic chunk of code. in other words, neither of above protections needed.
since there's no need protect fields, , since it's necessary see them (for instance, compare if 2 objects equal), they're visible within class.
Comments
Post a Comment