Reaching outward from a multiply-nested class
[37]It doesn’t matter how deeply an inner class may be nested—it can transparently access all of the members of all the classes it is nested within, as seen here:
//: c08:MultiNestingAccess.java
// Nested classes can access all members of all
// levels of the classes they are nested within.
class MNA {
private void f() {}
class A {
private void g() {}
public class B {
void h() {
g();
f();
}
}
}
}
public class MultiNestingAccess {
public static void main(String[] args) {
MNA mna = new MNA();
MNA.A mnaa = mna.new A();
MNA.A.B mnaab = mnaa.new B();
mnaab.h();
}
} ///:~
You can see that in MNA.A.B, the methods g( ) and f( ) are callable without any qualification (despite the fact that they are private). This example also demonstrates the syntax necessary to create objects of multiply-nested inner classes when you create the objects in a different class. The “.new” syntax produces the correct scope, so you do not have to qualify the class name in the constructor call.