title: Java: accessing protected fields from inner class
body: <p>Recently I've faced a problem getting a runtime error <code>java.lang.IllegalAccessError</code> when trying to access from inner class a protected field declared in outer's parent class that was loaded by a different class loader. Briefly:</p>
  <ol>
  <li>Class <code>Parent</code> has protected field <code>p</code>.</li>
  <li>Class <code>Outer</code> extends <code>Parent</code>.</li>
  <li>Class <code>Inner</code> is an inner class defined in class <code>Outer</code>.</li>
  <li>Inside <code>Inner</code> class there's a code: <code>Outer.this.p</code>.</li>
  <li>All classes are declared in the same package.</li>
  </ol>
  <p>Normally it's compiled and runs fine until <code>Parent</code> and <code>Outer</code> class are loaded by different class loaders. In this case we get <code>java.lang.IllegalAccessError</code> when trying to access <code>Outer.this.p</code> from <code>Inner</code>.
  I found an old bug report (which appeared to be a feature) describing this behavior:</p>
  <p><a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6258289" rel="noreferrer">https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6258289</a></p>
  <p>But resolution sounds contradictive to me:</p>
  <blockquote>
  <p>The key is that in the failing case the inner class isn't in the same
  package (and isn't a subclass of) ConcreteCommand/AbstractCommand.
  This is simply a violation of the Java specification for protected
  classes.</p>
  </blockquote>
  <p>It sounds correct. But if we declare <code>Parent</code> and <code>Outer</code> classes in different packages but load with the single class loader (simply create sample console app without any jar loadings) we don't get any errors. So technically it's a violation of Java spec for protected classes but since we use an inner class it works.</p>
  <p>So we have different behavior for two cases of &quot;different packages&quot;.</p>
  <ol>
  <li>Declared in different packages, loaded by single class loader - OK.</li>
  <li>Declared in single package, loaded by different class loaders - NOT OK.</li>
  </ol>
  <p>Could someone give a clear explanation of how inner class gets access to parent's fields and why it works differently for two cases?</p>