In Java, inner 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 inner class static
when it does not need that reference can lead to problems with garbage collection or escape analysis.
Is is 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());
}
}