In Java, nested classes can be either static or not. If they are static, they do not contain a reference to the pointer of the containing instance (they are also not called inner classes anymore, they are called nested classes).
Forgetting to make an nested class static when it does not need that reference can lead to problems with garbage collection or escape analysis.
Is it possible to make an anonymous inner class static as well? Or does the compiler figure this out automatically (which it could, because there cannot be any subclasses)?
For example, if I make an anonymous comparator, I almost never need the reference to the outside:
Collections.sort(list, new Comparator<String>(){ int compare(String a, String b){ return a.toUpperCase().compareTo(b.toUpperCase()); } }
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
staticnested classes if they don’t use their implicitthisreference.Edit: Tom Hawtin – tackline says that if the anonymous class is created in a static context (e.g. in the
mainmethod), the anonymous class is in factstatic. But the JLS disagrees:Roedy Green’s Java Glossary says that the fact that anonymous classes are allowed in a static context is implementation-dependent:
Edit 2: The JLS actually covers static contexts more explicitly in §15.9.2:
So an anonymous class in a static context is roughly equivalent to a
staticnested class in that it does not keep a reference to the enclosing class, even though it’s technically not astaticclass.