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


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 contents. Some IDE's suggest that we transform the variable into final , in this way, its content becomes immutable, but then the error changes, and it becomes the attempt to access content that cannot be changed.

However, if we just read its content, even without modifying it to final , no error is presented 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 it inside the anonymous class, not only can its content be read, but it is also allowed to change it, 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(){

            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 it's not a problem linked only to its scope, so what's the point of restricting access to a local variable in this way, different from the class variable? What kind of impact could allowing this kind of change to have, to have this restriction?


To answer briefly – and I'm no Java expert – this is because of the way Java handles closures . What Java makes available to the anonymous class are not the variables themselves (that is, references to certain values), but their values. So, if the variable is changed in the outer scope, it will not be reflected in the anonymous class. In the same way, as you have only one value detached from the original variable, it is not possible to change it – if the language allowed, this change would only have an effect within the anonymous class, and that would be confusing.

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

Source : Why are only final variables accessible in anonymous class? , reply from Jon Skeet

Scroll to Top