在同一个类另一个对象的访问私有字段字段、对象、在同一个

2023-09-02 21:24:15 作者:空港里的旧少年。

class Person 
{
   private BankAccount account;

   Person(BankAccount account)
   {
      this.account = account;
   }

   public Person someMethod(Person person)
   {
     //Why accessing private field is possible?

     BankAccount a = person.account;
   }
}

请忘掉设计。我知道,面向对象指定的私人对象是私有的类。我的问题是,为什么OOP设计,使得私人领域具有一流级别的访问和不是对象级别的访问?

Please forget about the design. I know that OOP specifies that private objects are private to the class. My question is, why was OOP designed such that private fields have class-level access and not object-level access?

推荐答案

我也有点好奇的答复。

I am also a bit curious with the answer.

最满意的答案,我觉得是Artemix在这里另一篇文章(我重命名ACLASS与Person类): Why有类级别的访问修饰符,而不是对象级?

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?

private修饰符强制封装的原则。

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

当人的实例访问其他人实例的内部 - 你可以肯定的是这两种情况下总是知道的人实施的细节。如果内部人过程中的逻辑改变 - 所有你需要做的是改变人的code

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.