When I use a non final variable from an inner class, I have a compile error :
public static void main(String[] args) {
String s = "hello";
s += "world";
Object myObj = new Object() {
public String toString() {
return s; // compile error
}
};
System.out.println(myObj);
}
However, I can fix this by adding a dummy final variable tmp
that references the other variable I would like to access :
public static void main(String[] args) {
String s = "hello";
s += "world";
final String tmp = s;
Object myObj = new Object() {
public String toString() {
return tmp; // that works!
}
};
System.out.println(myObj);
}
This process of adding a temporary final variable could be easily automatized, by a compiler for example.
My question is : why does the compiler do not perform automatically that simple change that allows us to get rid of this error ?