Why is it not possible to modify local variables when accessed within anonymous classes?

10

When trying to access a local variable from a method of an anonymous class in java, we usually get a syntax error if we try to modify its content. Some IDE's suggest that we transform the variable into final , so that its content becomes immutable, but then the error changes, and becomes the attempt to access content that can not be changed.

However, if you only read its content, even if you do not modify it to final , no error is displayed and the code works normally, with the copying of the content being done without problems.

But when you create a class variable and try to access within the anonymous class, not only can you read its contents, but it is also allowed to be changed, as can be seen in the example below:

public class AccessLevelVariableTest {

    private String oneVariable = "oneVariable";


    public void myMethod() {

        String localVariable = "localVariable";

        JButton btn = new JButton();

        btn.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent evt){

                oneVariable = localVariable; //isso é permitido
                System.out.println(localVariable); //isso é permitido
                localVariable = oneVariable; // isso ocorre erro de sinxate

            }
        });
    }
}

If the local variable is seen by the anonymous class, I believe that it is not a problem only related to its scope, so what is the meaning of restricting access to a local variable in this way, different from the class variable? What kind of impact does this type of change allow to have to be restricted?

    
asked by anonymous 23.03.2017 / 14:56

2 answers

8

Responding briefly - and I'm not a Java expert - this is due to the way Java handles closures. What Java makes available to the anonymous class are not the variables themselves (ie, references to certain values), but their values. So if the variable is changed in the outer scope, this will not be reflected in the anonymous class. In the same way, as if there is only one value unlinked from the original variable, it can not be changed - if the language allowed, this change would only have effect inside the anonymous class, and that would be confusing.

This probably run was a deliberate choice, to avoid the additional complexity that this would require of the compiler. Already C # works differently (with very similar syntax), because it made a different choice.

Source : Why are only end variables accessible in anonymous class? , Jon Skeet's answer

    
27.03.2017 / 03:32
2

localVariable only exists during the myMethod() method execution. Since the created object may exist in the scope outside the method, the variable localVariable will no longer exist.

    
27.03.2017 / 14:40