title: Access a variable using parent reference type in java
body: <p>I have created 2 classes - <code>Parent</code> and <code>Child</code>, both like this:</p>
  
  <p><strong>Parent.java</strong></p>
  
  <pre><code>public class Parent {
      String name = "Parent";
  }
  </code></pre>
  
  <p><strong>Child.java</strong>    </p>
  
  <pre><code>public class Child extends Parent {
      String name = "Child";
  }
  </code></pre>
  
  <p>The Child class is shadowing the parent class instance variable <code>name</code>.</p>
  
  <p>I have created a main program like this:</p>
  
  <p><strong>Test.java</strong></p>
  
  <pre><code>public class Test {
  
      public static void main(String[] args) {
          Parent p = new Parent();
          Child c = new Child();
  
          System.out.println(p.name);
          System.out.println(c.name);
  
          Parent pc = new Child();
          System.out.println(pc.name);
      }
  
  }
  </code></pre>
  
  <p>The output of the program is this:</p>
  
  <pre><code>Parent
  Child
  Parent
  </code></pre>
  
  <p>Now I am not clear on when I try to access <code>pc.name</code> then I am getting output as <code>Parent</code> as per the above output instead of <code>Child</code>.</p>
  
  <p>My understanding was like this, I created a reference variable <code>pc</code> of type <code>Parent</code> but it points to <code>Child</code> object as er my program. So during run-time time of the program, java creates an object in heap memory for the child class and since the child class is shadowing the <code>name</code> variable, the output of <code>pc.name</code> will be <code>Child</code>. But as per the program my understanding was not correct and this concept applies to only methods that are overriden by child class.</p>
  
  <p>Can you please explain why it is different in the case of instance variable compared to methods?</p>