Saturday, March 1, 2014

What is the use of anonymous classes in java? Can we say that usage of anonymous class is one of the advantages of java?
share|improve this question
17 
It's not so much an advantage of Java as it is a way to work around the lack of closures in Java. – Eric Wilson Sep 21 '12 at 11:53
add comment

11 Answers

up vote107down voteaccepted
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object which certain "extras" such as overloading methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        // do something.
    }
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
share|improve this answer
3 
Or you could refactor duplicate anonymous inner classes into one method with the anonymous inner class (and possibly some other duplicated code). –  Tom Hawtin - tackline Dec 14 '08 at 17:13
6 
You know...for that past 3 days I've been reading and rereading the official Java tutorials over, and over and over again to try and understand the whole Anonymous Inner Class thing. You accomplished in roughly 3 paragraphs what 4 pages from the creators of the language couldn't. Thank you sooooo much. –  AbeLinkonApr 14 '13 at 2:37
 
Great answer but a quick question. Does it mean Java can live without anonymous inner classes and they are like extra option to pick from? –  PK' Feb 23 at 20:37
add comment

3 comments: