2

In effective java second edition, the author says,

It is possible, although rare, to establish the association manually using the expression enclosingInstance.new MemberClass(args). As you would expect, the association takes up space in the nonstatic member class instance and adds time to its construction.

What does enclosingInstance.new MemberClass(args) mean? I googled for this and couldn't find anything. Can someone explain to me and shed some light? I have to take a seminar on this topic...

Tom Thomas
  • 619
  • 2
  • 8
  • 24
  • 2
    You can read up [this post](http://stackoverflow.com/a/19350126/1679863) to know in details about inner class. – Rohit Jain Jan 11 '14 at 11:09

1 Answers1

4

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();
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194