This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

An anonymous class can be static?????

 
Leandro Oliveira
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is an anonymous class in a static method static???
thanks!
 
Sarma Lolla
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question of static/final wouldn't arise for an anonymous inner class as you are creating the object on the same line as the class is declared.
And for any further subclassing this class is not available. The class scope ends in the very same line.
For the above reason for anonymous class you can't use strictfp/public/protected/private/abstract also.
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>>is an anonymous class in a static method static???
No, an anonymous class is always an inner class. It is never static. (JLS 15.9.5)
However, if an anonymous class is declared in a static method, the JLS says the anonymous class �occurs in a static context�. Therefore, the class has no reference to an object of the enclosing class and cannot access instance fields and methods of the enclosing class. (JLS 8.1.2)
[ March 18, 2003: Message edited by: Marlene Miller ]
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's compare anonymous classes, one declared in a static method, another in a non-static method.

javap -private Test$1

javap -private Test$2

Notice how the second anonymous class has a field that refers to a Test object. The compiler added that field so that the anonymous class can access instance methods and instance fields of the Test object.
[ March 18, 2003: Message edited by: Marlene Miller ]
[ March 18, 2003: Message edited by: Marlene Miller ]
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would you like to know all possible places where an inner class (which normally has a reference to an object of an enclosing class) occurs in a static context?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic