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?