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
157 views
in Technique[技术] by (71.8m points)

java - Private member accessibility

I have a use case, which I have simplified as the below program:

public class A {
   private int x = 100;

    class B {
       private int y = new A().x;
    }

  public static void main(String []s) {
    System.out.println(new A().new B().y);
  }
}

This program runs fine and prints 100.

As per the docs ( Access Modifiers ): private modifier makes sure that the field is accessible only within its own class. But in above program it seems to be contradicting the same.

Does this mean that?

  1. Inner class can access private members of outer class.
  2. Private variable of the inner class can be accessed in outer class.

Please help me understand.

question from:https://stackoverflow.com/questions/65850622/private-member-accessibility

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

1 Reply

0 votes
by (71.8m points)

The Java Language Specification is a better source of precise information about the language.

In this case, the relevant part is in clause 6.6.1:

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level type (§7.6) that encloses the declaration of the member or constructor.

That "within the body of the top level type" is the important part.

So basically, within the body of the same top level type (A in your case), all the code (whether written in a nested type or not) can access any private constructor/member declaration within the same body (whether declared in a nested type or not).


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

...