Back
What is the use of anonymous classes in Java? Can we say that the usage of an anonymous class is one of the advantages of Java?
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come helpful when creating an instance of an object with some "extras" such as major methods, without having to subclass a class.
I tend to try it as a shortcut for attaching a program listener:
button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// do something}});
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this approach makes coding a little bit faster, as I don't need to make an extra class that performs ActionListener-- I can just instantiate an unknown inner class without really making a separate class.
I only use this method for "quick also ruthless" tasks were making an entire class feel worthless. Having multiple anonymous inner classes that do the identical thing should be refactored to an actual class, be it an inner class or a separate class.
31k questions
32.8k answers
501 comments
693 users