From Java to Groovy (5.3. The similarities and differences between closures and anonymous internal classes) __java

Source: Internet
Author: User
Tags anonymous closure

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**/}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.