title: Java: protected access across packages
body: <p>I would like to understand what's happening in the example below (where a protected member is being accessed from outside the package through a subclass).</p>
  
  <p>I know for classes outside the package, the subclass can see the protected member only through inheritance.</p>
  
  <p>There are two packages: <code>package1</code> and <code>package2</code>.</p>
  
  <ol>
  <li><p><code>package1</code>: <code>ProtectedClass.java</code></p>
  
  <pre><code>package org.test.package1;
  
  public class ProtectedClass {
  
      protected void foo () {
          System.out.println("foo");
      }
  }
  </code></pre></li>
  <li><p><code>package2</code>: <code>ExtendsprotectedClass.java</code></p>
  
  <pre><code>package org.test.package2;
  
  import org.test.package1.ProtectedClass;
  
  public class ExtendsprotectedClass  extends ProtectedClass {
  
      public void boo() {
          foo(); // This works, 
                 // since protected method is visible through inheritance
      }
  
      public static void main(String[] args) {
          ExtendsprotectedClass epc = new ExtendsprotectedClass();
          epc.foo(); // Why is this working? 
                     // Since it is accessed through a reference,
                     // foo() should not be visible, right?
      }
  }
  </code></pre></li>
  <li><p><code>package2</code>: <code>UsesExtendedClass.java</code></p>
  
  <pre><code>package org.test.package2;
  
  public class UsesExtendedClass {
  
      public static void main(String[] args) {
          ExtendsprotectedClass epc = new ExtendsprotectedClass();
          epc.foo(); // CompilationError: 
                     // The method foo() from the type ProtectedClass
                     // is not visible
      }
  }
  </code></pre></li>
  </ol>
  
  <p>It is understood that the <code>boo()</code> method in <code>ExtendsprotectedClass</code> can access <code>foo()</code>, since protected members can be accessed through inheritance only.</p>
  
  <p>My question is, why is the <code>foo()</code> method working fine when accessed through a reference in the <code>main()</code> method of <code>ExtendsprotectedClass</code>  but <em>will not work</em> when accessed through the <code>epc</code> reference in <code>UsesExtendedClass</code>?</p>