Is it possible to make anonymous inner classes in Java static?

No, you can’t, and no, the compiler can’t figure it out. This is why FindBugs always suggests changing anonymous inner classes to named static nested classes if they don’t use their implicit this reference.

Edit: Tom Hawtin – tackline says that if the anonymous class is created in a static context (e.g. in the main method), the anonymous class is in fact static. But the JLS disagrees:

An anonymous class is never abstract (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1). An anonymous class is always implicitly final (§8.1.1.2).

Roedy Green’s Java Glossary says that the fact that anonymous classes are allowed in a static context is implementation-dependent:

If you want to baffle those maintaining your code, wags have discovered javac.exe will permit anonymous classes inside static init code and static methods, even though the language spec says than anonymous classes are never static. These anonymous classes, of course, have no access to the instance fields of the object. I don’t recommend doing this. The feature could be pulled at any time.

Edit 2: The JLS actually covers static contexts more explicitly in §15.9.2:

Let C be the class being instantiated, and let i be the instance being created. If C is an inner class then i may have an immediately enclosing instance. The immediately enclosing instance of i (§8.1.3) is determined as follows.

  • If C is an anonymous class, then:
    • If the class instance creation expression occurs in a static context (§8.1.3), then i has no immediately enclosing instance.
    • Otherwise, the immediately enclosing instance of i is this.

So an anonymous class in a static context is roughly equivalent to a static nested class in that it does not keep a reference to the enclosing class, even though it’s technically not a static class.

Leave a Comment