Understanding the creation of a non static member class in Java as described in Effective Java book

StackOverflow https://stackoverflow.com/questions/11556649

  •  21-06-2021
  •  | 
  •  

Question

Following is from Effective Java:

The association between a nonstatic member class instance and its enclosing instance is established when the former is created; it cannot be modified thereafter. Normally, the association is established automatically by invoking a nonstatic member class constructor from within an instance method of the enclosing class. 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 is Bloch saying here by "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." ?

Was it helpful?

Solution

He means you can establish the connection in at least two ways. Given

public class Outer {
    public class Inner {
    }
    void f() {System.out.println(new Inner());}
}
Outer x = new Outer();

If you call

x.f()

then the value you print is an inner object linked to x.

But one can also invoke:

x.new Inner();

to create a new inner object linked to x as well.

Bloch is saying the second way is rare. I'm not sure why; I have used it in the past.

See a live demo

class Outer {
    String name;
    public Outer(String name) {
        this.name = name;
    }

    public class Inner {
        public String toString() {
            return "I belong to " + Outer.this.name;
        }
    }

    void f() {
        System.out.println(new Inner());
    }

    void g(Outer a) { 
        System.out.println(a.new Inner());
    }
}

class Main {
    public static void main(String[] args) {
        Outer x = new Outer("x");
        Outer y = new Outer("y");
        x.f();
        x.g(y);      
    }
}

Output:

I belong to x
I belong to y
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top