Java this keyword

this is a reference variable in Java. It refers to the current object. It can be used inside the method or constructor of the class. this can be used to refer current object from within an instance method or constructor.

this can be used in many contexts like-

  • Invoke current class constructor
  • Invoke current class method
  • Return the current class object
  • Pass an argument in the constructor call.
  • Pass an argument in the method call.

Another use of this keyword is that it is not allowed two or more variable have the same name inside a class scope. Here we can see that the most common use of this keyword is to eliminate the confusion between class attributes and parameters with the same name. 

Let’s have a look at below example


We had used this keyword in the given example and we got output as a=5. If we omit the keyword in the given example then output will be a=0.

See the below example without this keyword.


this’ keyword in a different context

this with constructor

In the given example, ‘this’ is used to invoke the current class constructor.


Using this to return the current class instance

In this example, this keyword will use to return the current class instance.


Using this as a method parameter-


Using this to invoke current class method


Variable hiding in java with ‘this’ keyword

this keyword can be useful for variable hiding. In Java, we cannot take the same name for two instances; however, it is possible to take a local variable, instance variable, and mother parameter with the same name. In this process, the local variable hides the instance variable; this is called variable hiding.



Pin It on Pinterest

Share This