Usage of static inner classes
Why is it good to have static inner classes? When an inner class is not static it holds a reference to its main class. If your inner class does nothing with the main class the reference is completely useless and only takes some memory. Nothing really harmful, though.
Here’s the list of situations I prefer to use static inner classes:
- Data Holders. I often use custom information holders in code. A good example of holder is a Map.Entry interface. Though it’s not a class but interface, it still gives an excellent example of how you can work with data. If you need to operate groups of related objects, the use of holders can’t be overrated.
- Comparators and Filters. These two are very common and are number one to be considered for being static.
- Runnable tasks. When I need to execute some code in another thread I don’t usually do it like this: “new Thread(new Runnable() {…}).start()”. Runnable here is clearly some task and I put it in separate inner static class. The code quickly becomes clear and pretty. In contrast to multi-level mess we end up with in the first sample, we have “new Thread(new MyTask()).start()” or, if you use executors, “executor.execute(new MyTask())”, which is much better, in my opinion.
- Cell Renderers. It’s common practice nowadays to use common cell renderers to produce better data views. In most cases, a cell renderer doesn’t make any sense out of a context of main class, where a corresponding list is created. It’s clear that if you do not intend to reuse a cell renderer, there’s no need to pull it out of the main class. I leave them there and often make them static.
- Adapters. Often a type of data I have doesn’t match a type of data I need to provide to some component as an input. In this cases I use adapters and I always make them static.
- Data Models. When it comes to custom models for some specific lists and tables, I often leave them as inner classes if they aren’t complex enough and do not deserve their own dedicated file.
Well, there are neither rules of how and when use static inner classes nor terrible need in them, but they help us to keep our code simple, organized and optimal by clarifying our intentions to communicate our ideas with other coders better.