Java Private Field Visibility

主宰稳场 提交于 2019-11-28 20:37:18

It's accessible from different instances of the same class.

According to this page (bolding mine):

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class.

For clarity I'll rewrite this line:

if ( t.privateInt == this.privateInt )

We can agree that "this.privateInt" should be allowed: you are accessing it from within the instance of class Test that the message "equals" has been sent to.

It's less clear that "t.privateInt" should be visible, because t is a separate instance of class Test and we are not executing inside its equals method. However java allows this since both objects (t and this) are of the same class Test and can see each others private members.

Mike's quite correct; you are confusing objects (instances of a class) with the class itself. The members are private to the class, not any particular instance of the class.

I recall being just as surprised about this when I was new to Java.

You are referencing it from within the same class. Thus, you know what you are doing and does not need to be protected from yourself.

One big reason that access to the private members of other instances is allowed is to permit "copy" functions -- they would be pretty much impossible otherwise. Also, if you didn't allow access by other instances, what would you allow for static methods?

The private variables of another instance of the same class can be accessed. This is because you are dealing with the implementation of the class, directly, which requires you to know about its internal, 'private' variables anyway.

The simple answer to this confusion is to remember that private field are visible only and only in the class where they are initialize( and defined)....So when you make an object of the class inside the class, you can always access the private field of that class through the object reference. May be you feel its difficult but just think private field is just like a public field when you are using it inside the class where it is defined.

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