Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Anonymous Classes a bad idea?

Tags:

java

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.

like image 553
Allain Lalonde Avatar asked Nov 06 '08 16:11

Allain Lalonde


2 Answers

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.

like image 181
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet


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() {...}
});
like image 33
Vinze Avatar answered Sep 27 '22 23:09

Vinze