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);
}
}
}
printA
:B
accessesa.var1
which is private inA
– Haymow