This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Anonymous class  RSS feed

 
jacob deiter
Ranch Hand
Posts: 587
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I hope every concept in java has pros. Can anyone explain what are the real-time use of Anonymous class. Please do not write theatrical definition which are available in Java books.If explain with example is more appreciative
 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use anonymous classes for actions in Swing most of the time:

If I don't I end up writing dozens of named sub classes of AbstractAction in some of my programs.
 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And lots of us add anonymous ActionListeners to our Buttons. They look rather similar to Rob's example, and most books have them in. In fact I think a book which doesn't teach how to write an anonymous ActionListener probably isn't worth reading!
 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, I hardly use ActionListeners for any of my buttons. I prefer (Abstract)Action - you can use a single Action object to share the text, icon, mnemonic and accelerator for multiple buttons. That includes JMenuItem.

And since Action extends ActionListener you get the event handling as well
 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rob Prime:
And since Action extends ActionListener you get the event handling as well
So you do use ActionListeners

I see your point, they do appear to be an improvement on ActionListener.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And just to throw in a non-GUI based example, I will use it a lot when using Runnables:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!