I need to change a variable in the upper class from the nested (I guess it could be called this way, I am new to java, I searched it but couldn't find it)
The code:
public class mainClass {
public static void main(String[] args) {
boolean variableToChange = false;
Timer myTimer = new Timer();
TimerTask myTimerTask= new TimerTask() {
public void run() {
if(variableToChange==false) { //it can read the variable
variableToChange = true; //but it can't change it?!
//it triggers and error here
}
}
};
myTimer.scheduleAtFixedRate(myTimerTask, 0, 100);
}
}
You can access, but cannot change variableToChange
since it's inside an anonymous inner-class and declared outside it.
From JLS 8.1.3:
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.
Variables declared outside an anonymous inner-class are considered final
inside it. You are probably using Java 8 where where final
can be implicit.
A "dirty" workaround (which isn't recommended due to synchronization issues, but works) is to declare:
final boolean[] variableToChange = new boolean[1];
And then you will be able to change it inside:
variableToChange[0] = true;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments