Java Private Field Visibility

后端 未结 6 488
轻奢々
轻奢々 2020-12-14 10:05

So I was making a class the other day and used Eclipse\'s method to create the equals method when I realized that it generated the following working code:

相关标签:
6条回答
  • 2020-12-14 10:25

    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?

    0 讨论(0)
  • 2020-12-14 10:29

    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.

    0 讨论(0)
  • 2020-12-14 10:31

    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.

    0 讨论(0)
  • 2020-12-14 10:38

    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.

    0 讨论(0)
  • 2020-12-14 10:48

    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.

    0 讨论(0)
  • 2020-12-14 10:49

    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.

    0 讨论(0)
提交回复
热议问题