Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (10.2k points)

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?

1 Answer

0 votes
by (46k points)

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() {


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.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jan 25, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)

Browse Categories