gpt4 book ai didi

java - 访问同一类中另一个对象的私有(private)字段

转载 作者:IT老高 更新时间:2023-10-28 12:06:45 25 4
gpt4 key购买 nike

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 指定私有(private)对象是类私有(private)的。我的问题是,为什么 OOP 被设计成私有(private)字段具有类级别的访问权限,而 不是对象级别的访问权限

最佳答案

我也有点好奇这个答案。

我找到的最令人满意的答案来自 Artemix 的另一篇文章(我正在用 Person 类重命名 AClass): 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.

编辑:请投票 Artemix 的回答。我只是复制粘贴而已。

关于java - 访问同一类中另一个对象的私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17027139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com