Private member accessibility

Viewed 147

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.

2 Answers

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).

Does this mean that ?

Private variable of the inner class can be accessed in outer class.

Yes. The following works.

public class A {
    public void someMethod() {
        // this references the private field
        // in the inner class
        System.out.println(new B().x);
    }

    class B {
        private int x = 42;
    }
}    

Does this mean that ?

Inner class can access private members of outer class.

Yes. The following works.

public class A {
    private int x = 100;

    class B {
        public void someMethod() {
            // this references the private field
            // in the outer class
            System.out.println(x);
        }
    }
}

Please help me understand.

The examples above should help.

Related