Way2Java

Using this Keyword Example Java

this Keyword Java

"this" keyword refers an object, to say, the current object. Observe the following program and pay attention to this.salary.

public class Officer3 
{
  int salary;
  public void display(int salary)
  {
    this.salary = salary;
  }
  public static void main(String args[])
  {
    Officer3 o1 = new Officer3();
    o1.display(5000);
    System.out.println(o1.salary);     // 5000
  }
}
Output screen of Officer3.java

In the display() method, local variable and the instance variable are same, salary. That is, local variable clashes with instance variable. If "this" is removed in display() method, o1.salary in the main() method prints 0. "this" refers the object o1 as with o1 the display() method is called. Now we can make one rule, if a method is called with an object, the instance variables inside the method are linked with the object implicitly. Now, this.salary becomes o1.salary internally and one memory location is created. If "this" is removed, both salaries are treated as local variables and thereby the compiler does not create any memory location. Use always "this" keyword to differentiate a local from instance variable when they clash. C++ people, call "this keyword" as "this pointer".

Explanation on parameters passing to method is available at Three Great Principles – Data Binding, Data Hiding, Encapsulation.