title: Java Inheritance - this keyword
body: <p>I searched online for similar question, but could not find it. So, posting here.</p>
  
  <p>In the following program why the value of 'i' is printed as 100?</p>
  
  <p>AFAIK 'this' refers to the current object; which in this case is 'TestChild' and the class name is also correctly printed. But why the value of the instance variable is not 200?</p>
  
  <pre><code>public class TestParentChild {
      public static void main(String[] args) {
          new TestChild().printName();
      }
  }
  
  class TestChild extends TestParent{
      public int i = 200;
  }
  
  class TestParent{
      public int i = 100;
      public void printName(){
          System.err.println(this.getClass().getName());
          System.err.println(this.i); //Shouldn't this print 200
      }
  }
  </code></pre>
  
  <p>And moreover the output of the following is as i expected. The child class method is invoked, when i call "<strong>this.test()</strong>" from Parent class.</p>
  
  <pre><code>public class TestParentChild {
      public static void main(String[] args) {
          new TestChild().printName();
      }
  }
  
  class TestChild extends TestParent{
      public int i = 200;
      public void test(){
          System.err.println("Child Class : "+i);
      }
  
  }
  
  class TestParent{
      public int i = 100;
      public void printName(){
          System.err.println(this.getClass().getName());
          System.err.println(this.i); //Shouldn't this print 200
          this.test();
      }
      public void test(){
          System.err.println("Parent Class : "+i);
      }
  }
  </code></pre>