This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes Anonymous class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Anonymous class" Watch "Anonymous class" New topic
Author

Anonymous class

jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
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

Joined: Oct 27, 2005
Posts: 19725
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
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

Joined: Oct 27, 2005
Posts: 19725
    
  20

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
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
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

Joined: Jan 28, 2003
Posts: 4181
    
  21

And just to throw in a non-GUI based example, I will use it a lot when using Runnables:


Steve
 
Consider Paul's rocket mass heater.
 
subject: Anonymous class