Field shadowed by local variable from the point of view of an anonymous class [duplicate]

StackOverflow https://stackoverflow.com/questions/22703363

  •  23-06-2023
  •  | 
  •  

Question

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?

Was it helpful?

Solution

You can use

A.this.x

Since the anonymous Runnable class is an inner class of the A class.

The concept of shadowing determines that x in

System.out.println(x);

is referring to the local method parameter variable x, but that is not final so you can't access it within the anonymous class, not in Java 7 and below at least. You can in Java 8, which may be confusing.

Don't use the same name for your variables in the same compilation unit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top