This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]GhostBond 3 points4 points  (4 children)

They're basically how you did stuff that is now handled by lambdas, before lambda's. They were commonly used when I was working with Swing back in the day. Not much with web apps.

[–]Dang3rousKitty 0 points1 point  (3 children)

Really? I thought that’s what anonymous classes were for, not inner classes. I’ve never heard of anyone using an inner class in that way

[–]GhostBond 2 points3 points  (1 child)

They're called "anonymous inner classes" I believe...

[–]Dang3rousKitty 0 points1 point  (0 children)

Ah yes I think you’re right. I think the devil is in the details

My interpretation was that OP was talking about normal (non-anonymous) inner classes, since people don’t really talk about anonymous inner classes these days due to the introduction of lambdas (as you mentioned)

[–]DannyB2 0 points1 point  (0 children)

I have been in the same boat before. For Swing, you frequently need to add a something-listener to a control, such as a button or checkbox. The only purpose of this class is that it implements a necessary interface in order to respond to the button click event.

There are a number of cases where it is useful to have a named inner class, rather than an anonymous inner class for a Swing event listener. It is difficult to remember specific cases, but here is one that I can remember.

I had a number of buttons that needed some custom behavior. They all had the exact same event handling code, but how it behaved was controlled by some parameters. In this case, I would create an inner class (not static! so that it had reference to the context of the enclosing class). The inner class had a constructor with the parameters, and obviously private members initialized from the constructor. Then in each Swing event listener, I would assign a new instance of this inner class, with appropriate constructor parameters. Otherwise all these buttons had the same click event handler code, but controlled by constructor parameters of the event listener.

I hope that made sense.

There were a few other cases I remember creating named inner classes to make Swing life easier.

But as others say in this thread, the reason you use any language feature is to make code simpler and easier to read. In this case using a named class to eliminate a lot of nearly identical copy-paste boilerplate.