Is usage of anonymous classes in Java considered bad style or good?

I tend to use anonymous inner classes in situations where I don't need to have a full-blown class just to perform some task. For example, if I want to implement an ActionListener or Runnable, but I don't think having an inner class would be necessary. For example, for starting a simple Thread, using an anonymous inner class might be more readable:

public void someMethod()
{
    new Thread(new Runnable() {
        public void run()
        {
            // do stuff
        }
    }).start();
}

In certain cases, such as the example above, it can increase readability, especially for one-time tasks, as the code that is to be executed is all written in one spot. Using an inner class would "delocalize" the code:

public void someMethod()
{
    new Thread(new MyRunnable()).start();
}

// ... several methods down ... //

class MyRunnable implements Runnable
{
    public void run()
    {
        // do stuff
    }
}

That said, however, if there is going to be cases where the same thing is going to be repeated, it should indeed be a separate class, be it a regular class or an inner class.

I tend to use anonymous inner classes in programs where I am just trying things out rather than have it as a central feature of an actual application.


One more good use of anonymous inner class is when you need to initialize collections like ArrayList and Set. This practice is also known as double brace initialization For example ,

private static final Set<String> VALID_CODES = new HashSet<String>() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR2D");
}};

Obviously, this is not limited to collections; it can be used to initialize any kind of object -- for example Gui objects:

 add(new JPanel() {{
setLayout(...);
setBorder(...);
add(new JLabel(...));
add(new JSpinner(...));
}});