Why am I able to print this field in a static method?
anonymous-class, eclipse, java
Solution
JLS § 15.8.4 says "The value of an expression of the form `TypeName.this` is the n'th lexically enclosing instance of `this`". Since there is no enclosing instance of Main in your example, the code is not valid.
In javac, the code produces the error "non-static variable `this` cannot be referenced from a static context". The fact that it compiles in Eclipse appears to be an obscure bug in Eclipse (which has its own compiler).
Problem
``` public class Main { private final int value = 3; public static Runnable buildRunner() { return new Runnable() { @Override public void run() { System.out.println(Main.this.value); } }; } } ``` I am using Eclipse Kepler, with JRE 7. In the `buildRunner` method - why I am able to see the `this` of Main? What is the 'this' of Main in a static method? Why does this compile? I can only do that if `value` is final. I cannot call instance methods of Main and stuff, but value is not decalred `static`! Furthermore, if I want to use in the `buildRunner` method, outside the `run` method of the `new Runnable`, the compiler stops me from doing that.