javasemanticsdsl

Why can an instance of a class access private fields of another instance of its own type?


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)?


Solution

  • First you have to ask "why have private fields at all?"

    Private fields are primarily for encapsulation: a consumer of a class shouldn't have to know the internals of that class' implementation, and in fact those internals should be actively hidden from the consumer. Otherwise, if a user relied on those internals, 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:

    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 and deployed 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.