在同一个类另一个对象的访问私有字段 [英] Access private field of another object in same class

查看:246
本文介绍了在同一个类另一个对象的访问私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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类): <一href="http://stackoverflow.com/questions/16354728/why-have-class-level-access-modifiers-instead-of-object-level">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.

这篇关于在同一个类另一个对象的访问私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆