After using them a while I can't help but feel that the hoops you're forced to jump through when using anonymous classes are not worth it.
You end up with final
all over the place and no matter what the code is more difficult to read than if you'd used a well named inner class.
So what are the advantages of using them? I must be missing something.
The advantage is that it's an implementation of closures. It's clunky, but it's the best we've got in Java at the moment. In other words, you don't have to create a new class just for the sake of preserving some state which you've already got as a local variable somewhere.
I have an article comparing C# and Java closures, and why they're useful in the first place, which might help.
Well I usually only use it when needing an implementation of an interface for a single purpose (and an interface with few functions or the code because really fast ugly)... like in the following example :
this.addListener(new IListener(){
public void listen() {...}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With