I know anonymous classes save typing when it comes to implementing Listener and similar stuff. They try to be a replacement for some usages of closures.
But what does the community think about the value of this language-feature? Does it make sense and do you use it regularly? Does it make the code clearer, more understandable and more maintainable? Or do anonymous classes make the code less readable?
What is your opinion, and please have examples/arguments handy to support your opinion?
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.