enclosingInstance.newMermberClass(args) in java – effective java text

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…

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *