File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

'this' in a static nested class

 
Preeti Yarla
Ranch Hand
Posts: 69
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Preeti Yarla
Ranch Hand
Posts: 69
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic