title: Protected access across package through reference variable in java
body: <h2><a href="https://i.stack.imgur.com/vs5lG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vs5lG.png" alt="enter image description here"></a></h2>
  
  <p>For the above hierarchy, Below is the code from <code>pkg1</code>,</p>
  
  <pre><code>package ProtectedAccess.pkg1;
  
  public class T {
  
      protected int f;
      protected void m(){
  
      }
  
  }
  </code></pre>
  
  <hr>
  
  <p>Below is the code from <code>pkg2</code>, where  <code>test2</code> is tested by replacing <code>X</code> with class <code>T</code> or  <code>A</code> or <code>B</code> or <code>C</code> or <code>S</code> or <code>D</code> or  <code>E</code> or <code>F</code> or <code>G</code> or <code>H</code>.</p>
  
  <pre><code>package ProtectedAccess.pkg2;
  import ProtectedAccess.pkg1.*;
  
  class A extends T {}
  class B extends T{}
  class C extends B{}
  
  public class S extends B{
      void test1(){
          f = 42;
          m();
      }
  
      void test2(X  t){
          t.f = 42;
          t.m();
      }
  
  }
  
  class D extends S{}
  class G extends D{}
  class E extends S{}
  class H extends E{}
  class F extends S{}
  </code></pre>
  
  <p>--</p>
  
  <p>1)
  If <code>X</code> is replaced with <code>T</code> or <code>A</code> or <code>B</code> or <code>C</code>, then compiler error.</p>
  
  <p>2)
  If <code>X</code> is replaced with <code>S</code> or <code>D</code> or <code>E</code> or <code>F</code> or <code>G</code> or <code>H</code>, then things code works fine.</p>
  
  <p>How do I understand the working of two scenarios from aforementioned points? Please help!!!</p>