Oleksiy Khilkevich
Oleksiy Khilkevich

Reputation: 809

How JVM stores the link to enclosing class within inner class?

Having the following code:

public class Main  {
    private Main() {}

    class Test extends Main {
        {
            System.out.printf("This: %h\nEnclosed in: %h\n", 
                 this, Main.this); 
            System.out.printf("Main.this is instance of %s\n\n" , 
                 Main.this.getClass());
        }
    }

    public static strictfp void main(String... args) {
        new Main().new Test();
    }
}

Here are the questions:

  1. Were in memory does JVM store the reference Main.this ?
  2. Is this area (see 1) of memory reserved for normal top-level class instances?

Upvotes: 0

Views: 95

Answers (1)

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

Think of the non-static inner class as something similar to:

public class Main {

  static class Test extends Main {
    private final Main _outer;
    ...
  }
}

Where the _outer reference is established during construction. At the GC level, instances of outer and inner class are not differentiated at all.

Upvotes: 3

Related Questions