且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:直接从同一个类的另一个实例访问私有字段

更新时间:2023-11-22 19:11:46

不,不是。私有变量和方法无法从其他类访问的原因是允许您更改类的内部,而无需更改使用该类的所有代码(并且防止类的用户例如设置变量)一个它从未应该具有的值。)

No, it's not. The reason that private variables and methods are not accessable from other classes is to allow you to change the internals of your class without having to change all the code that uses the class (that and to prevent the user of your class from e.g. setting a variable to a value that it's never supposed to have).

如果你使用其他对象的私有变量不会伤害任何东西,因为如果你重组你的类的内部,无论如何你必须改变类中的代码。

If you use private variables of other objects that doesn't hurt anything, because if you'd restructure your class's internals, you'd have to change the code inside the class anyway.