This Keyword in Java

In this tutorial we will learn about this Keyword in Java. In very simple words this keyword in Java references to object of the current class. At present, it might be sound confusing. But you will find it easy after checking the following example:

Example code:

Class ThisExample{
      String name;
      public ThisExample(String name){
         this.name=name;
      }
  
      public void show(){
         System.out.println("Hello "+name);
      }
     
      public static void main(String args[]){
          ThisExample obj=new ThisExample("Owlbuddy");
          obj.show();
      }
}

In the above example, you can see we have used this keyword inside the constructor of the class. If you will see very clearly in code you will find that variable name is defined to time. Once as a global variable in class and then as a local variable in Constructor. It means when we assign local name value to global name value that will be confusing for the compiler.

But we used this keyword to overcome this problem. As we discussed earlier this keyword refers to the object of the current class. So it means when we wrote this.name it means we were referring to a global variable and when we wrote simple name it means were referring to a local variable of the constructor.

This keyword can be used in several ways. such as in constructor overloading (we will cover this topic in upcoming tutorials), to differentiating global and local variable names in Methods(Same as Constructor) etc.

Spread the love