11
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 Fdis suggest that we turn the variable into final
, thus, its content becomes immutable, but then the error changes, and becomes the attempt to access a content that cannot be changed.
However, if we only read its content, even not modifying to final
, no error is presented and the code works normally, with the copy of the content being made without problems.
But when you create a class variable and try to access within the anonymous class, not only can you read its content, 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 viewed by the anonymous class, I believe it is not a problem linked only to its scope, so what is the point of restricting access to a local variable in this way, different from the class variable? What kind of impact could such a change cause to have such a restriction?
ah, I think it would be much simpler to ask why a property or whatever, like
protected
orprivate
cannot be directly referenced.– Edilson
@Edilson but that’s not really my question, about access modifiers I’ve read right here on the site and understood. The doubt is about variables of even smaller scope.
– user28595
Local variable being accessed for reading is allowed? I confess I never noticed it. I thought it was forbidden to read as well as write.
– Piovezan