The similarities and differences between closures and anonymous internal classes.
As mentioned earlier, the maximum limit for anonymous inner classes is the ability to reference variables (their ability to reference variables): They can only reference class variables (class variables) and local final variables (locally final variables); its grammar is also puzzling, and seems verbose. Even anonymous inner classes cannot be reused and can only be used in declared classes. In contrast, closures do not have these annoying limitations, which can refer to any variable within the scope of the closure, concise syntax that can be reused and assigned to variables. Because closures are instances of Groovy.lang.Closure objects, closures have extra functionality outside of anonymous inner classes.
To illustrate the difference between the two, consider how to use anonymous inner classes in Java to add events to a button:
JButton button = new JButton ("click Me");
Button.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {//do something
}
});
Using groovy implementations, the code is simple and easy to read:
JButton button = new JButton ("Click Me")
button.actionperformed = {/your logic here**/}