I'm trying to run this code:
class A {
int x = 123;
public void f(int x) {
new Runnable() {
public void run() {
System.out.println(x);
}
}.run();
}
static {
A a = new A();
a.f(33);
}
}
But it's giving me an error:
$ javac A.java && java A
A.java:6: local variable x is accessed from within inner class; needs to be declared final
System.out.println(x);
^
1 error
The x
argument isn't final
, so it shouldn't be accessible from the anonymous class, yet the code fails to compile. It looks like the println
line is trying to use the x
argument instead of the x
field. Why? How can I tell it I want the x
field?