Why can private member variable be changed by class instance?

∥☆過路亽.° 提交于 2019-11-29 02:55:41

Private members are accessible to any code within the program text of that class (including within nested types). It has nothing to do with which instance of the class you're dealing with.

I don't believe this violates encapsulation - the API is still separated from the implementation, but the implementation "knows" about itself regardless of which instance it's looking at.

I believe that in some other languages this isn't how accessibility works, but it definitely is for C# and Java. (Java has slightly different rules about what can access private members, but the translated code for what you've written would still work.)

This is because C# enforces class-level privacy and not object-level privacy.

Most mainstream languages enforce the same policy, i.e. C#, C++ and Java. I think the reason are:

1) because developers are accustomed to that kind of policy;

2) because object-level privacy would become much too tedious in return of very few advantages.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!