There's a very simple program:
public class A {
public static void main(String[] p) {
final Runnable r = new Runnable() {
public void run() {
System.out.println(r);
}
};
r.run();
}
}
And this gives:
$ javac A.java
A.java:6: variable r might not have been initialized
System.out.println(r);
^
1 error
- Why?
- How can a Runnable reference a variable pointing to it?
(In the real code, there is one more level (a listener), and referencing via this
does not work)
The working code is:
So it is possible to "unfinal" a variable using an auxiliary object.
It looks like this construct (an auxiliary object whose fields may be accessed from a Runnable) is exactly what the designers of Java tried to disallow. :)