This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes An anonymous class can be static????? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "An anonymous class can be static?????" Watch "An anonymous class can be static?????" New topic
Author

An anonymous class can be static?????

Leandro Oliveira
Ranch Hand

Joined: Nov 07, 2002
Posts: 298
is an anonymous class in a static method static???
thanks!
Sarma Lolla
Ranch Hand

Joined: Oct 21, 2002
Posts: 203
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

Joined: Mar 05, 2003
Posts: 1391
>>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

Joined: Mar 05, 2003
Posts: 1391
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

Joined: Mar 05, 2003
Posts: 1391
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?
 
Don't get me started about those stupid light bulbs.
 
subject: An anonymous class can be static?????