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

1

8

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

}

}
Haymow answered 10/8, 2012 at 23:56 Comment(2)
look at printA : B accesses a.var1 which is private in AHaymow
While the standard isn't too specific on this matter directly, the private modifier limits to the current class' file.Tomasatomasina
G
9

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.

Goren answered 11/8, 2012 at 0:0 Comment(5)
Ah.. so nested classes don't provide additional scope. I guess thats clear from the fact that Main can access it.Haymow
Exactly. Since they're defined inside Main, it would make no sense to scope them, since there's no real "Encapsulation" (at least not in the same way different separate classes offer).Goren
I was hoping there was. Thanks for the help!! I'll accept your answer as soon as I can ( there is a 10 min time limit )Haymow
@Hugo What do you mean by " that two instances of a same class can access each other's private memebres.". Example?Guaiacum
@hajder In class Bike, assuming color is private: public boolean compare(Bike anotherBike) { return this.color.equals(anotherBike.color) } is fine.Goren

© 2022 - 2024 — McMap. All rights reserved.