Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

language features - Java Private Field Visibility

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:

class Test {
  private int privateInt;
  [...]
  public boolean equals(Object obj) {
    [...]
    Test t = (Test) obj;
    if ( t.privateInt == privateInt ) {
    [...]
  }
}

t.privateInt..???? It's suppose to be private! So I guess there is one more field visibility other than private, protected, package protected and public.

So what is happening here? How is this called? Where would somebody use this? Doesn't this break encapsulation? What if the class didn't have a mutator and I changed this? Does this happen to C++ as well? Is this an OO idiom? If not, then why did Java do it?

Generally, where can I find information about this?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...