It means "create a new instance of MemberClass
, using enclosingInstance
as the reference for the new instance".
An inner class has an implicit reference to its enclosing class - normally if you just call new MemberClass()
within an instance method, the enclosing class instance is implicitly this
, but using enclosingInstance.new MemberClass()
you can explicitly specify a different one. You can also use this approach to create an instance of the inner class from a static method, or indeed from an entirely different class.
A demonstration may help to explain:
class Outer {
private String name;
Outer(String name) {
this.name = name;
}
class Inner {
void showEnclosingName() {
System.out.println("Enclosing instance name: " + name);
}
}
void demo() {
Outer outer = new Outer("Other Outer");
Inner inner1 = new Inner(); // Implicitly this.new Inner();
Inner inner2 = outer.new Inner();
inner1.showEnclosingName(); // Prints Original Outer
inner2.showEnclosingName(); // Prints Other Outer
}
public static void main(String[] args) {
Outer outer = new Outer("Original Outer");
outer.demo();
}
}