tags:

views:

321

answers:

4

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.

+1  A: 

I generally limit anonymous classes to just a few lines. Anything longer than, say 5, make a named class.

sblundy
Or at least a static nested class
matt b
+7  A: 

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.

Jon Skeet
I was under the impression that Java's anonymous inner classes did NOT close on their environment, but don't have a citation or example to support myself.
hark
They do, but the only variables you can access from the outer scope are those which are declared final.
Eli Courtwright
I'm not sure about this either. If I understand closures, you can pass around a reference to a closure and it retains references to the bound variables of the enclosing scope where it was created. I think that's missing in anonymous classes in Java.
Bill the Lizard
It basically fake closures. It copies the values into the new class. Given that you've only got read-only access anyway, and the variables are final, it's reasonably close to closures. It's a copy of the environment instead of the environment itself, but that's very often close enough.
Jon Skeet
+3  A: 

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() {...}
});
Vinze
+1  A: 

I recommend you this article that I found very enlightening.

You say that final keyword is all over the place but, with a local class, you still have to pass the state of the enclosing class witch can also be bad for readability.

bruno conde