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

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

问题描述

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 指定私有对象是类私有的.我的问题是,为什么将 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 类):为什么使用类级访问修饰符而不是对象级?

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.

这个想法是外部世界"不应该对 Person 的内部流程进行更改,因为 Person 的实现可能会随着时间的推移而改变(并且您必须更改整个外部世界以修复实现中的差异 - 这几乎是不可能的).

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

当 Person 的实例访问其他 Person 实例的内部时 - 您可以确保两个实例始终知道 Person 的实现细节.如果 Person 流程的内部逻辑发生变化 - 您所要做的就是更改 Person 的代码.

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.

投票 Artemix 的回答.我只是复制粘贴它.

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

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

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