Home Java Recursively nested classes

Recursively nested classes

by admin

Just came across an interesting feature of nested classes in Java – they can be nested recursively and infinitely!

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

You can expect both instances of the Test class to reference the Main class which includes them. However, if you compile and run it, you get an interesting picture
This: 6665e41
Enclosed in: 2ab600af
Main.this is instance of class Main
This: 796686c8
Enclosed in: 6665e41
Main.this is instance of class Main$Test
This: 3a1af2bc
Enclosed in: 796686c8
Main.this is instance of class Main$Test

So Main.this in the last two instances is of type Main$Test, and the instances themselves refer to each other, building up a chain!
This peculiarity makes me think of a more efficient LinkedList implementation. But I wonder where JVM stores the link to the include class. If the reference is implicitly an additional field of the nested class, then in terms of memory the implementations will be the same. But if memory for this reference is reserved for all classes, the game for extra eight bytes per element is worth a candle 🙂
UPD: turns out to be solved by the first option – the compiler introduces synthetic fields. So there’s no gain – the link used in LinkedList.Node will just be synthetic

You may also like