I want to understand better the visibility of instance fields of containing class to an Anonymous inner class (AIC).
There have been lots of talks that AIC has an implicit reference to the containing class' instance (When exactly is it leak safe to use (anonymous) inner classes?). With that logic, even when an AIC is instantiated within a static method, it should have access to the instance fields of the containing class. But I can't find a way to test this as the compiler gives errors.
For e.g., in the below code, I get: "Non-static field 's' can't be referred from a static context" by the compiler when I refer 's' within print() method of the AIC:
public interface TestInterface {
void print();
}
public class AICTest {
public String s = "something";
public static void main( String[] args ) {
new TestInterface() {
@Override
public void print() {
System.out.println( s ); **<-- compilation error**
}
}.print();
}
}
Could you suggest if it's possible for the AIC instance to access 's' in the above example?
Edit/Answer I want to clarify that I am aware that static methods have access to class members and instance methods have access to instance & class members. The confusion was more about the general statement that AIC always have an implicit reference to containing class' object. This clearly is not the case for AIC initialised within a static method. @shmosel shared a link which answers my question (Is it possible to make anonymous inner classes in Java static?): "So an anonymous class in a static context is roughly equivalent to a static nested class in that it does not keep a reference to the enclosing class, even though it's technically not a static class.".
System.out.println(new AICTest().s);
– Elliott Frisch