Originally posted by Preeti Vadlamudi: I ran the following code assuming that the compiler would throw an error because I used this in a static context ... Can someone please tell what 'this' refers to in a static nested class? ...
A nested class being "static" only means that the class is not associated with any instance of the enclosing class. Because of this, you were able to create an instance of the static nested class (Inner) without ever creating an instance of the enclosing class (Outer1).
Within an instance of a nested class (static or otherwise), "this" refers to the current instance, just as it does within an instance of a non-nested class. That's the output you're seeing.
Your method name (seeOuter) implies that you were expecting "this" to refer to the enclosing instance. But to do that, you would use "EnclosingClassName.this" -- not just "this." (In your example, Outer1.this.) That will not work if the nested class is static, because there is no enclosing instance. I think that is the error you were expecting.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Sep 08, 2007
Thanks for the descriptive example.
Previously I did not understand that there is nothing static about the class itself and that a static nested class is a normal class which is just a static member of the outer class.