Tutorial :Anonymous vs named inner classes? - best practices?


I have a class, let's call it LineGraph, that renders a line graph. I need to subclass it, but the derived class is only used in one place and is coupled to the class that uses it. So I am using an inner class.

I see two ways to do this:

Anonymous inner class

public class Gui {      LineGraph graph = new LineGraph() {          // extra functionality here.      };  }  

Named inner class

public class Gui {      MyLineGraph graph = new MyLineGraph();        private class MyLineGraph extends LineGraph {          // extra functionality here.      }  }  

I am not a fan of anonymous inner classes, because frankly I just think it looks really ugly. But in the case of a subclass that's only used in one place, is a named inner class overkill? What is the accepted practice?


One advantage of anonymous inner classes is that no one can ever use it anywhere else, whereas a named inner class can be used (if only by the class that created it if made private). It's a small distinction, but it does mean that you can protect an inner class from being accidentally used elsewhere.

Also, using the anonymous inner class gives anyone reading your code a head's up - "this class is being used just here and nowhere else." If you see a named inner class, someone might think it'd be used in multiple places in the class.

They are very similar, so neither point is a game-changer. I just think it helps for clarity if you use anonymous inner classes for one-offs, and named inner classes when it's used multiple times within the class.


(Counter point to Daniel Lew)

One disadvantage of anonymous inner classes is that no one can ever use it anywhere else, whereas a named inner class can be used (if only by the class that created it if made private). It's a small distinction, but it does mean that you can help ensure that an inner class is not accidentally recreated elsewhere.

Also, using the anonymous inner class gives anyone reading your code a harder time as they then have to parse this class that came out of nowhere. Using a named inner class you are able to organize the source more.

I have seen cases where there are two (or more) anonymous inner classes with the exact same code. In GUIs especially (where you may have multiple controls performing the same action) this can crop up (and I am talking production code, not code that my students have written).

The readability issue goes both ways, some people find anonymous inner classes better as it lets you see what is going on in once place, others find it a distraction. That part comes down to personal preference.

Also making an class static is more efficient, if you are declaring an anonymous inner class in an instance then there will be more overhead, which, if you don't need access to the instance variables, is wasteful (but probably not worth worrying about until it presents as a problem).

My personal preference is to use non-anonymous classes as they allow for more flexibility when the code is modified later.


Why do you need to subclass it? If it's just to override an existing virtual method, I think an anonymous inner class is okay. If you're adding extra functionality, I'd use a named class. I'd make it a nested class though (i.e. with the static modifier) - I find them easier to reason about :)


Do the simplest thing that could possibly work: Use the anonymous inner class.

If you later find that you need a broader scope, then refactor the code to support this.

(You would do the same with variables -- putting them in the most specific scope. It makes sense to do the same with other source assets.)


Anonymous inner classes are hard to debug in Eclipse (thats what I use). You will not be able to look at variable values/inject values by simply right clicking.


A disadvantage of inner classes is that they can not be static. This means that will hold a reference to the outer class that contains them.

Non-static inner classes can be an issue. For example we recently had an inner class being serialised, but the outer class was not serializeable. The hidden reference meant that the outer class would also be serialised, which of course failed, but it took a while to find out why.

Where I work, static inner classes are encouraged in our coding best practices (where possible) as they carry less hidden baggage and are leaner.


My personal rule of thumb: If the anonymous inner class is going to be small, stick with an anonymous class. Small being defined as around 20 - 30 lines or less. If it is going to be longer, it starts to be unreadable in my opinion, so I make it a named inner class. I remember once seeing a 4000+ line anonymous inner class.


Anonymous inner classes would generally be the way to go. I find them very readable. However, if the instance of that class ever needs to be serialized (even if only because it's a field of something else), I would strongly recommend using named inner classes. The names of anonymous inner classes in the bytecode can change very easily, and this can break serialization.


Anonymous classes can't have a constructor, since they don't have a name. If you need to pass other variables than those in the constructor(s) of the class you're extending, you should use a (static) named inner class. This can sometimes be overcome by using final variables in the surrounding method/code, but it's a bit ugly imho (and can lead to what Robin said).


I don't have a problem with simple anonymous classes. But if it consists of more than a few lines of code or a couple of methods, an inner class is more clear. I also think that under certain conditions they should never be used. Such as when they must return data.

I have seen code where a final array of 1 item is used to pass data back from a call to an anonymous inner class. Inside the method of the anon class, the single element is set, then this 'result' extracted once the method is complete. Valid, but ugly code.


Anonymous classes:

  • cannot have anything static in the definition (static class, static field, static initializer, etc.)
  • fields cannot be inspected in Eclipse
  • cannot be used as a type (Foo$1 myFoo=new Foo$1(){int x=0;} doesn't work)
  • cannot be located using the class name in Eclipse (searching for Foo$1 doesn't work for me)
  • cannot be reused

Anonymous classes can, however, have an initializer like {super.foo(finalVariable+this.bar);}

Named inner classes don't have these limitations, but even if one is used exclusively in the middle of a long procedure, the declaration will have to be moved up to the next named class.

I personally prefer anonymous inner classes if the restrictions don't apply because:

  • I know any additional fields are only referenced in the class definition.
  • Eclipse can convert them to nested classes easily.
  • I don't need to copy in variables I want to use. I can just declare them final and reference them. This is especially useful when I have lots of parameters.
  • The code that interacts is close together.


I think what you've done makes perfect sense in this case and either way you look at it, I think you are really splitting hairs with this particular issue. They are both so similar and either will work.


I think this is a matter of taste. I prefer to use anonymous classes for Functors. But in your case, I'd use an inner class, since I think you'll be packing more than just a few lines of code in there, perhaps more than just a method. And it would emphasise the fact that it's adding functionality to the superclass, by putting it inside the class, rather than hidden somewhere in a method. Plus, who knows, maybe someday you might need the subclass else where. This, of course, depends on how much you know about how your software will evolve. Other than that, just flip a coin. :)


Just had this discussion today with my coworker and was digging around for popular opinion.

I am in agreement with TofuBeer. If your code has more than 2 lines, it's probably not a 'one-off' and might be re-used some day. If you are creating a form using an MVC pattern, you might have 20 controllable elements on a page instead of cluttering the view up with tons of anonymouse classes (hell your view was probably created using a GUI builder and the code was auto-genned making editing the source not even an option) you will likely feed each element to a controller. You can nest inner classes within the controller to handle each different handler/listener interface that your view requires. This organizes the code really well, especially if you have a convention that your handler class must be named using the GUI element name (like backButtonHandler for a backButtonElement). This worked really well for us, and we wrote an auto-registration tool (when you register a controller on a view, the view looks for inner-classes using the element name and uses them for a handler on each named element). This would not be possible with anonymous classes and makes the controller much more recyclable.

TLDR: when in doubt write a named inner-class. You'll never know if someone wants to re-use your code some day (unless it's 2 lines, then you have to wonder 'does this code smell?'). Code that is well organized has much higher benefits in the long term, especially when your project is in maintenance.


With anonymous inner classes, we cannot change the state of the including class members. They need to be declared as final.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »