I have been using new ActionListener() when creating an action listener, but I receive a warning when using this telling me I should replace it with lambda. Nothing changes with the actual functionality when I switch between the two, but I am just curious why lambda is better.
jb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { popUp.dispose(); } });
vs.
jb.addActionListener(e -> popUp.dispose());
>Solution :
Signal to noise ratio. addActionListener already tells us that it’s an action listener. The new ActionListener() part provides no information to the programmer. Likewise, every action listener has a actionPerformed, so specifying that explicitly is mostly pointless in the simple case. So since modern Java versions allow us to omit it, we should.
You would still want an anonymous class if you had some instance variables or other private methods inside the listener. Of course, in this case, you might be better suited to use a named inner class to begin with, since your needs have clearly expanded.
Basically, anonymous classes were a crux from before lambdas existed in Java. Both solve the same problem: "I’ve got a tiny piece of functionality and don’t want to give it a proper name since it’s trivial". So if you’ve got something trivial, you should use the shorter of the two. And if you’ve got something nontrivial, you should give it a name and document it.