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 doe
If limiting scope and access as much as possible is a good thing, then anonymous classes are very good. They are limited in scope to the one class that needs them. When that's appropriate, I'd say anonymous classes are good.
The instant you duplicate the same function, it becomes a bad idea. Refactor it into a public class that stands on its own. IDEs with refactoring features make that easy.
It depends what you compare them to. I'd rather have them than not have them, but then I'd rather be able to supply plain code blocks to methods like Arrays.sort() than having to explicitly create a class containing my implementation of compare().
I agree with what many others have said in that they are useful for small interfaces when only used once. But I would also add the restriction that if code external to the anonymous class has to be altered for it to work, then don't use an anonymous class.
If you have to start declaring variables as final to accommodate the anon class since it references them, then use an inner class instead. I have also seen some bad code smells where final arrays (of size 1) are used to return results from anon classes.
It makes sense to use them, but you must be aware of whats being done underneath. I only use them if I need a class to do something very specific that I don't need anywhere else.
Whether using anonymous class improves or degrades legibility is a matter of taste. The main issue is definitely not here.
Anonymous classes, like inner classes, carries a reference to the enclosing class, thus making non private things that without it would be. To be short, the this reference of the enclosing class may escape through the inner class. So the answer is: it is a very bad practice to use an inner class if it published itself, since that would automatically publish the enclosing class. for example:
changeManager.register(new ChangeListener() {
public void onChange(...) {
...
}});
Here, the anonymous ChangeLstener is passed to the register method of a ChangeManager. Doing so will automatically publish the enclosing class as well.
This is definitely a bad practice.
I use anonymous classes mostly for interfaces that have only a single method, i.e. Runnable or ActionListener. Most larger interfaces warrent their own classes or implementation in an already existing class. And as it is my opinion I don’t need arguments to support it.