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.
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...
+ 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.
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.