May 17, 2011

The this keyword in Java

The this keyword is used to refer to or access the "currently executing" object in a method. The this keyword can be used only in instance methods, and cannot be used within static methods. The this keyword is used to resolve the conflict when there is shadowing of variables in action (when an instance variable and local variable have the same name).

public class Test {

   private int i;

   public void m1() {
      int i;       // shadowing in action
      
      i = 3;       // assigns a value to the local variable
      this.i = 4;  // assigns a value to the instance variable 
   }
}

public class Driver {

   public static void main(String args[]) {
      Test t1 = new Test(); 
      t1.m1();                // 1

      Test t2 = new Test(); 
      t2.m2();                // 2
   }
}


At line 1, when m1() is invoked on the object referred to by t1, the this keyword is a reference to the t1 object. At line 2, when m1() invoked on the object referred to by t2, the this keyword now becomes a reference to the t2 object.

Thus, this is used to get hold of the reference to the currently executing object, from within the invoked instance method.

No comments:

Post a Comment