I found that two nested classes in java have access to each other's private members. Why is this the case? Is it a bug or is this what the standard specifies?
The following code compiles and runs without error.
public class Main {
public static void main(String args[]) {
A a = new A();
a.var1 = 12;
B b = new B();
System.out.println(a.var1);
b.printA(a);
}
private static class A {
private int var1;
}
private static class B {
private int var2;
public void printA(A a) {
// B accesses A's private variable
System.out.println(a.var1);
}
}
}
Yes, it's expected. The variable being private means it cannot be accessed outside the scope of Main
, but it can be accessed anywhere inside of this scope, in a very similar way that two instances of a same class can access each other's private members.