title: Can Anonymous inner class instantiated within a static method has access to instance members of containing class?
body: <p>I want to understand better the visibility of instance fields of containing class to an Anonymous inner class <strong>(AIC)</strong>.</p>
  
  <p>There have been lots of talks that AIC has an implicit reference to the containing class' instance (<a href="https://stackoverflow.com/questions/10864853/when-exactly-is-it-leak-safe-to-use-anonymous-inner-classes">When exactly is it leak safe to use (anonymous) inner classes?</a>). 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. </p>
  
  <p>For e.g., in the below code, I get: <em>"Non-static field 's' can't be referred from a static context"</em> by the compiler when I refer 's' within print() method of the AIC:</p>
  
  <pre><code>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 ); **&lt;-- compilation error**
              }
          }.print();
  
      }
  }
  </code></pre>
  
  <p>Could you suggest if it's possible for the AIC instance to access 's' in the above example?</p>
  
  <p><strong>Edit/Answer</strong>
  I want to clarify that I am aware that static methods have access to class members and instance methods have access to instance &amp; 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 (<a href="https://stackoverflow.com/questions/758570/is-it-possible-to-make-anonymous-inner-classes-in-java-static">Is it possible to make anonymous inner classes in Java static?</a>): <em>"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.".</em></p>