Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sibling nested classes in Java have access to each other's private members

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);
    }

}

}
like image 585
Chip Avatar asked Aug 10 '12 23:08

Chip


1 Answers

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.

like image 140
WhyNotHugo Avatar answered Sep 22 '22 19:09

WhyNotHugo