This question is about whether to make an inner class in Java
static or not. I searched around here and on StackOverflow, but couldn't really find any questions regarding the design implications of this decision.
The questions I found are asking about the difference between static and non-static inner classes, which is clear to me. However, I have not yet found a convincing reason to ever use a non-static inner class in Java - with the exception of anonymous classes, which I do not consider for this question.
Here's my understanding of the effect of using static inner classes:
- Less coupling: We generally get less coupling, as the class cannot directly access its outer class's attributes. Less coupling generally means better code quality, easier testing, refactoring, etc.
Class: The class loader need not take care of a new class each time, we create an object of the outer class. We just get new objects for the same class over and over.
For a non-static inner class, I generally find that people consider access to the outer class's attributes as a pro. I beg to differ in this regard from a design point of view, as this direct access means we have a high coupling and if we ever want to extract the inner class into its separate top-level class, we can only do so after essentially turning it into a static inner class.
So my question comes down to this: Am I wrong in assuming that the attribute access available to non-static inner classes leads to high coupling, hence to lower code quality, and that I infer from this that (non-anonymous) inner classes should generally be static?
Or in other words: Is there a convincing reason why one would prefer a non-static inner class?