This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes 'this' in a static nested class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark " Watch " New topic
Author

'this' in a static nested class

Preeti Yarla
Ranch Hand

Joined: Sep 08, 2007
Posts: 69
I ran the following code assuming that the compiler would throw an error because I used this in a static context.



But I got the following result:


Innerclass ref is: Outer1$Inner@1eed786



Can someone please tell what 'this' refers to in a static nested class? (Since static means belonging to a class and not to a object)


SCJP
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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
Preeti Yarla
Ranch Hand

Joined: Sep 08, 2007
Posts: 69
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: 'this' in a static nested class