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?
- Inner class can access private members of outer class.
- Private variable of the inner class can be accessed in outer class.
Please help me understand.
B
is a member of classA
, and therefore can access private members ofA
. Likewise sinceB
is a member ofA
, the static methodmain
(which is also part ofA
in this example) can access private members ofB
.B
is within "its own class" here with respect toA
. That's how the specification says it works.