Why should I use anonymous-classes? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why should I use anonymous-classes?

What should be the reason to override an method with an anonymous class? I do not see the advantage.

20th Apr 2020, 7:49 PM
Tim Suchland
Tim Suchland - avatar
3 Answers
+ 2
Hello Tim Suchland Expect for GUI programs I've never used anonymous classes. In principle you can use them if you need an interface or abstract class only for a single object. To stick with GUI. Imagine a Button. If you click this Button something should happen. For this you need the Interface ActionListener. But you know only the Button object needs this. (There are some more reasons but I want to keep it very easy). You don't want to implement the ActionListener for the whole class. And you don't want to write a normal extra class. Here you can use an anonymous class. A tiny javafx example: Button btn = new Button(); btn.setOnAction(new ActionListener(){ @Override public void actionPerformed{ //the stuff which should happen when you click the Button } }); Since java 8 you can use lambda expressions so you have a small compact anonymous class. As you can see, the anonymous class has no name and no meaning outside the Button method. To be continued...
20th Apr 2020, 8:49 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Part 2: If you want the Button has it's own class which is tailored to it. And you don't need to think about it anymore.
20th Apr 2020, 8:50 PM
Denise Roßberg
Denise Roßberg - avatar
0
Thanks Denise Roßberg for the answer. This helps me to understand the concept better. My only feeling is, that this is not the best coding style.
21st Apr 2020, 5:14 AM
Tim Suchland
Tim Suchland - avatar