- Non-static classes inside a container
The example indeed leads to the advantage of having a non-static inner class:
class ABC {
LMN obj;
List<Xyz> xyzs = new ArrayList<>();
public class Xyz {
@customAnnotation LMN lmn;
public void foo(){
ABC.this.obj = lmn;
}
}
... new Xyz(); // Passes the this of ABC.
}
One might make the constructor of Xyz private in order to allow only ABC the correct creation of Xyzs.
Namely that ever Xyz knows the ABC that created it: ABC.this
. Useful for containers.
- For method/stream related value holders
For static inner classes it can be a local use inside the class itself, or a parameter/result/exception class for a method in ABC, bound to the usage of class ABC.
Such a class is useful, as the API will not change when the parameter of a method is just Xyz, but Xyz gets and additional field. Would the method get an additional field, all usages would need to be updated. For a library that could make backward compatibility more awkward (a new method).
For lambdas with a classical forEach, or for loops such a static class might be useful too.
- Already often used: local enums
Finally enum
s defining a domain value range, are often also local to a class.
- Uses in standard java
In standard java there is the case of Character with extensive Unicode support in the form of inner classes Character.SubSet, UnicodeBlock, UnicodeScript
.