Access private field of another object in same class

I am also a bit curious with the answer.

The most satisfying answer that I find is from Artemix in another post here (I'm renaming the AClass with Person class): Why have class-level access modifiers instead of object-level?

The private modifier enforces Encapsulation principle.

The idea is that 'outer world' should not make changes to Person internal processes because Person implementation may change over time (and you would have to change the whole outer world to fix the differences in implementation - which is nearly to impossible).

When instance of Person accesses internals of other Person instance - you can be sure that both instances always know the details of implementation of Person. If the logic of internal to Person processes is changed - all you have to do is change the code of Person.

EDIT: Please vote Artemix' answer. I'm just copy-pasting it.


Good question. It seems that object level access modifier would enforce the Encapsulation principle even further.

But actually it's the other way around. Let's take an example. Suppose you want to deep copy an object in a constructor, if you cannot access the private members of that object. Then the only possible way is to add some public accessors to all of the private members. This will make your objects naked to all other parts of the system.

So encapsulation doesn't mean being closed to all of the rest of the world. It means being selective about whom you want to be open to.

Tags:

.Net

C++

Java

Oop