Reputation: 483
Please consider the following code snippet.
public class HelloWorld{
private static class InnerA{
private int _a;
private InnerA( int a ){
_a = a;
}
private int getA(){
return _a;
}
}
private static class InnerB{
private InnerB(){
InnerA inner_a = new InnerA( 1 ); //isn't the constructor of InnerA private??
System.out.println( inner_a.getA() ); //isn't getA() a private function of InnerA??
}
}
public static void main(String []args){
InnerB b = new InnerB();
}
}
My questions are:
InnerA
's constructor is marked as private, but why is it called successfully from inside InnerB
's constructor?
Why can getA()
, which is a private method of InnerA
, be called
from inside InnerB
? I thought marking the method as private
would prevent it from being used outside of InnerA
?
Upvotes: 0
Views: 519
Reputation: 434
The documentation says:
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
Upvotes: 0
Reputation: 3304
Nested static classes have access to all members of its enclosing class, including private members.
They do not get access to instance members, public or private, of its enclosing instance. However, if you pass a method of a static nested class an instance of the enclosing class, the nested class would be able to access all members of the enclosing class, regardless of their access level.
Upvotes: 0
Reputation: 140319
From the language spec:
Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level type (§7.6) that encloses the declaration of the member or constructor.
Things inside the same top-level class are always accessible.
Upvotes: 2