Just came across an interesting feature of nested classes in Java - they can be nested into each other 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 that both instances of the Test class will reference the Main class that includes them. However, if you compile and run it turns out 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
That is, Main.this in the last two instances has the type Main $ Test, and the instances themselves link to each other, lining up in a chain!
This feature suggests thoughts of a more efficient implementation of LinkedList. That's just wondering where the JVM stores the link to the enclosing class. If the link is implicitly an additional field of the nested class, then the memory will be the same. But if the memory for this link is reserved for all classes, then the game for the extra eight bytes per item is worth the candle :)
UPD: it turns out everything is solved in the first embodiment - the compiler introduces synthetic fields. So there will be no gain - the link used in LinkedList.Node will simply be synthetic.