Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.
  • Single 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?

share|improve this question
2  
from Java tutorial: "Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access." – gnat May 12 '14 at 9:05
3  
Thanks for the tutorial quote, but this just re-iterates what the difference is, not why you would want to access the instance fields. – Frank May 12 '14 at 9:43
    
it's rather a general guidance, hinting on what to prefer. I added a more detailed explanation on how I interpret it in this answer – gnat May 12 '14 at 10:35
    
If the inner class isn't tightly coupled to the enclosing class, it probably shouldn't be an inner class in the first place. – Kevin Krumwiede Oct 5 '15 at 6:05
up vote 8 down vote accepted

Joshua Bloch in Item 22 of his book "Effective Java Second Edition" tells when to use which kind of nested class and why. There are some quotes below:

One common use of a static member class is as a public helper class, useful only in conjunction with its outer class. For example, consider an enum describing the operations supported by a calculator. The Operation enum should be a public static member class of the Calculator class. Clients of Calculator could then refer to operations using names like Calculator.Operation.PLUS and Calculator.Operation.MINUS.

One common use of a nonstatic member class is to define an Adapter that allows an instance of the outer class to be viewed as an instance of some unrelated class. For example, implementations of the Map interface typically use nonstatic member classes to implement their collection views, which are returned by Map’s keySet, entrySet, and values methods. Similarly, implementations of the collection interfaces, such as Set and List, typically use nonstatic member classes to implement their iterators:

// Typical use of a nonstatic member class
public class MySet<E> extends AbstractSet<E> {
    ... // Bulk of the class omitted

    public Iterator<E> iterator() {
        return new MyIterator();
    }

    private class MyIterator implements Iterator<E> {
        ...
    }
}

If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration, making it a static rather than a nonstatic member class.

share|improve this answer
1  
I'm not quite sure how/whether this adapter changes the view of the outer class MySet instances? I could envision something like a path-dependent type being a difference, i.e. myOneSet.iterator.getClass() != myOtherSet.iterator.getClass(), but then again, in Java this is actually not possible, as the class would be the same for each. – Frank May 12 '14 at 9:55
    
@Frank It's a pretty typical adapter class - it lets you view the set as a stream of its elements (an Iterator). – immibis Oct 5 '15 at 8:05
    
@immibis thanks, I'm well aware of what the iterator / adapter does, but this question was about how it is implemented. – Frank Oct 5 '15 at 10:32
    
@Frank I was saying how it changes the view of the outer instance. That's exactly what an adapter does - it changes the way you view some object. In this case, that object is the outer instance. – immibis Oct 5 '15 at 10:44

You are correct in assuming that the attribute access available to non-static inner classes leads to high coupling, hence to lower code quality, and (non-anonymous and non-local) inner classes should generally be static.

Design implications of decision to make inner class non-static are laid out in Java Puzzlers, Puzzle 90 (bold font in below quote is mine):

Whenever you write a member class, ask yourself, Does this class really need an enclosing instance? If the answer is no, make it static. Inner classes are sometimes useful, but they can easily introduce complications that make a program difficult to understand. They have complex interactions with generics (Puzzle 89), reflection (Puzzle 80), and inheritance (this puzzle). If you declare Inner1 to be static, the problem goes away. If you also declare Inner2 to be static, you can actually understand what the program does: a nice bonus indeed.

In summary, it is rarely appropriate for one class to be both an inner class and a subclass of another. More generally, it is rarely appropriate to extend an inner class; if you must, think long and hard about the enclosing instance. Also, prefer static nested classes to non-static. Most member classes can and should be declared static.

If you're interested, a more detailed analysis of Puzzle 90 is provided in this answer at Stack Overflow.


It is worth noting that above is essentially an extended version of the guidance given in Java Classes and Objects tutorial:

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.

So, the answer to the question you asked in other words per tutorial is, the only convincing reason to use non-static is when access to an enclosing instance's non-public fields and methods is required.

Tutorial wording is somewhat broad (this may be the reason why Java Puzzlers make an attempt to strengthen it and narrow it down). In particular, directly accessing enclosing instance fields has never been really required in my experience - in the sense that alternative ways like passing these as constructor / method parameters always turned easier to debug and maintain.


Overall, my (quite painful) encounters with debugging inner classes directly accessing fields of enclosing instance made strong impression that this practice resembles use of global state, along with known evils associated with it.

Of course, Java makes it so that damage of such a "quasi global" is contained within enclosing class, but when I had to debug particular inner class, it felt like such a band aid didn't help to reduce pain: I still had to keep in mind "foreign" semantic and details instead of fully focusing on analysis of a particular troublesome object.


For the sake of completeness, there may be cases where above reasoning doesn't apply. For example, per my reading of map.keySet javadocs, this feature suggests tight coupling and as a result, invalidates arguments against non-static classes:

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa...

Not that above would somehow make involved code easier to maintain, test and debug mind you, but it at least could allow one to argue that complication matches / is justified by intended functionality.

share|improve this answer
    
I share your experience on the problems caused by this high coupling, but I'm not ok with the tutorial's usage of require. You say yourself, that you never really required the field access, so unfortunately, this also does not fully address my question. – Frank May 12 '14 at 14:43
    
@Frank well as you can see, my interpretation of tutorial guidance (which seem to be supported by Java Puzzlers) is like, use non-static classes only when you can prove that this is required, and in particular, prove that alternative ways are worse. Worth noting that in my experience alternative ways always turned out better – gnat May 12 '14 at 14:49
    
That's the point. If it is always better, then why do we bother? – Frank May 12 '14 at 15:26
    
@Frank another answer provides compelling examples that this ain't always so. Per my reading of map.keySet javadocs, this feature suggests tight coupling and as a result, invalidates arguments against non-static classes "The set is backed by the map, so changes to the map are reflected in the set, and vice-versa..." – gnat May 12 '14 at 16:02

Some misconceptions:

Less coupling: We generally get less coupling, as the [static inner] class cannot directly access its outer class's attributes.

IIRC - Actually, it can. (Of course if they are object fields, it will not have an outer object to look at. Nonetheless, if it does get such an object from anywhere, then it can directly access those fields).

Single 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.

I'm not quite sure what you mean here. The class loader is only involved twice in total, once for each class (when the class is loaded).


Rambling follows:

In Javaland we seem to be a bit scared to create classes. I think it has to feel like a significant concept. It generally belongs in its own file. It needs significant boilerplate. It needs attention to its design.

Versus other languages - eg Scala, or maybe C++: There is absolutely no drama creating a tiny holder (class, struct, whatever) anytime that two bits of data belong together. Flexible access rules help you by cutting down the boilerplate, letting you keep the related code physically closer. This reduces your 'mind-distance' between the two classes.

We can wave away design concerns over the direct access, by keeping the inner class private.

(...If you'd asked 'why a non-static public inner class?' that's a very good question - I don't think I've ever yet found a justified case for those).

You can use them anytime it helps with code readability and avoiding DRY violations and boilerplate. I don't have a ready example because it doesn't happen all that often in my experience, but it does happen.


Static inner classes is still a good default approach, btw. Non-static has an extra hidden field generated through which the inner class refers to the outer.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.