This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/4…

Issue an overview

1.

A can only be final here. Why is that? How can I redefine a in the onClick () method without ensuring that it is a private member variable?

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5; }}); }Copy the code

2.

How can I return 5 * A after clicking?

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void }}); }Copy the code

Best answer

As noted in the comments, some of these become irrelevant in Java 8, and final can be implicit. However, only valid final variables can be used in anonymous inner classes or lambda expressions.

This is basically due to the way Java manages closures.

When you create an instance of an anonymous inner class, any variables used in the class will copy their values through an automatically generated constructor. He avoids the compiler having to automatically generate all sorts of extra types to hold the logical state of “local variables”, as in C# editors (when C# captures variables in anonymous functions, it actually captures variables – closures can update variables in a way that the method body can see, and vice versa).

Since the value has been copied into an instance of the anonymous inner class, it would look strange if the rest of the variable could be modified by the rest of the method – you might find that the code appears to be used with outdated variables (because that’s actually what’s going to happen… You will use copies taken at different times). Similarly, if you can make changes in an anonymous inner class, the developer might want those changes to be visible in the body of the closed method.