When working with user interface based Java programs, one way of attaching behaviour to a certain actions (e.g. to a button click) is through the use of anonymous classes. In the example below, the GUI framework is SWT, however I have the same issues with Swing or Android UI components. Namely the structuring of my programs.

MenuItem sampleMenuItem = new MenuItem(popupMenu, SWT.NONE);
sampleMenuItem.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent event) {

         // handle all table entries
         for (int i=0; i<10; i++) {


Of course, some might argue that the amount of code in the sample above already warrants for the creation of a dedicated class that contains the logic. This is also suggested by Sonar's "Anonymous classes should not have too many lines" rule.

Interestingly, this rule also specifies that:

squid : S1188 - While waiting for support of closure in Java, anonymous classes is the most convenient way to inject a behavior without having to create a dedicated class. But those anonymous inner classes should be used only if the behavior can be accomplished in a few lines. With more complex code, a named class is called for.

However, since closures have not yet arrived in Java, my question is whether there are any more elegant solutions than:

  • writing a bunch of code within anonymous classes which has all sorts of drawbacks (limited reuse, slower navigating through the code, ...)
  • creating a huge number of dedicated classes which themselves all might have very limited functionality (i.e.: over-engineering, ...)

To extend my question: I would also like to know what are the best practices with respect to this aspect of Java based UI applications? Are there any well established patterns?

  • You would use anonymous classes where the likelihood of code reuse is relatively low, and you need several implementations of an interface. This avoids you having to write a new class for each implementation. Have you seen this? Jan 23, 2014 at 21:51
  • @Robert, I'm aware about the fact that code attached to an anonymous class is normally not intended for reuse. However, I encountered a few instances where I would have liked to be able to do this nevertheless. E.g. In the case where a Button and a MenuItem need to execute the same code, but only with slight adaptations and without violating DRY. For this reason, I am looking for techniques that allow better separation and structuring of my code.
    – Jérôme
    Jan 24, 2014 at 21:08
  • You do that by promoting the anonymous class to an actual class. Jan 24, 2014 at 21:10
  • As mentioned in my question, this is one of the solutions that I know of. However, I am looking for other techniques or best practices in case they exist. However, if no such thing exists, and we have to choose between either creating an anonymous class or an actual class, this might be a valid answer too.. :-) In the past, I have worked with various GUIs in a bunch of different programming languages. And from Delphi to Visual Studio to even Eiffel [sic], I always considered the Java way using anonymous classes quite verbose in terms of LOC that are needed to achieve a result.
    – Jérôme
    Jan 24, 2014 at 21:24
  • 1
    That's because Java is inherently verbose. You can't fix stupid. Jan 24, 2014 at 21:26

2 Answers 2


The only pattern I've seen, that works is "When the code gets to hard to figure out what's going on, it's time to stop using an anonymous class.".

In your example, the method body is the anonymous class. I might move the "new SelectionAdapter" onto it's own line, to make the opening paren a little more obvious, but otherwise it's fine. Where you get into trouble is when a random person can no longer figure out where the anonymous class and method code are.

I've also create a private variable, or method to hold the anonymous class. I put that kind of thing at the bottom of the class, out of the way. It kinda sorta bridges the gap between a whole new class, and keeping it in the middle of the code. Some people consider it bad style though, but my general rule of thumb is to code for readability first.

  • I totally agree with respect to your first paragraph. However, it sometimes seems cumbersome to create a dedicated class, especially when something that starts out with a few lines grows over time. Up to now, I've never seen somebody assign anonymous classes to private variables at the end of the parent class. However, I can see the benefit of structuring the code without creating a lot of small dedicated classes. Even if it might be bad style, it partly answers my question with respect to which other techniques exist. +1
    – Jérôme
    Jan 24, 2014 at 21:16

Anonymous inner classes are a purely stylistic thing; they don't exist as such within the containing class at the level of the .class file which gets created during compilation; all anonymous inner classes DO create a separate .class file as though they were written as top level classes.

You can see this if you navigate to the output directory (typically named "out") and look for the inner class by name. You will see a separate class file for your inner class. As I recall its name is OuterClassName$InnerClassName.class. The constructor of an anonymous inner class (which is created even though you don't write it yourself) is passed a reference to "this" which of course is the containing outer class.

So don't base your decision on any concerns you have over "making a lot of classes". It's purely a stylistic thing.

When I started Java, anonymous classes looked like a big mess to me just because they violated the rhythm of the class which went something like variable variable method method then all of a sudden this pile of code appeared. Actually, they still mildly irritate me.

Their supposed advantage is that they make code comprehension easier- you don't have to go to some other file to see what the method of the anonymous inner class will do. But that's it.

So the decision is a stylistic one and nothing more. If you like it, use it, if not, don't.

just wanted to quickly add this- you might revisit your idea that containing limited functionality , say 1 short method, within a dedicated class constitutes over-engineering. The class , at least in Java, is the unit of cohesion. Over-engineering isn't measured in methods per class or even class count. O E is entirely orthogonal to both of these.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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