Line
b = new Test5(){{ value = 1 ;}};
instantiates an anonymous class that extends Test5 . However, since value is private, an anonymous class cannot access the instance variable of its superclass.
Since there is no variable called value visible to the anonymous subclass of Test5 , the compiler is looking for an alternative in the following area. In this case, the next area relates to the static method main . The compiler detects the Test5 instance Test5 , and it issues a warning because the instance variable cannot refer to the static context.
Here you have two alternatives:
I take it from your question that the first alternative is what you really want to do.
@Tom: The problem is not that the static area is scanned first. If that were the case, then alternative (1) would not work, because the value instance variable is still found and still cannot be specified.
@Ken: Your instanceMethod() does not do what you expect from this! Take a look at the following code:
class Test5A { private int value; public void instanceMethod() { Test5A a = new Test5A() {{ value = 1; }};
This sample code mimics the behavior of your class. If you compile and execute it, you will see that the output is "1 0".
While the initializer of the instance of the anonymous subclass in (A) looks like it assigns one instance of the instance of value , this variable is actually visible only in the superclass of the anonymous class. Instead, in line (A), the only visible variable called value is the instance variable of the Test5A instanceMethod() that instanceMethod() called on. Therefore, it changes to one.
Now increase the visibility of value :
class Test5B { protected int value; public void instanceMethod() { Test5B a = new Test5B() {{ value = 1; }}; System.out.println(this.value); System.out.println(a.value); } public static void main(String[] args) { new Test5B().instanceMethod(); } }
This time the output will be "0 1". value instance variable inherited by an anonymous subclass, and its visible to its instance initializer. Therefore, one is assigned to the correct instance variable.