Java this keyword

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

Output

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.

Output

this’ keyword in a different context

this with constructor

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

Output

Using this to return the current class instance

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

Output-

Using this as a method parameter-

Output-

Using this to invoke current class method

Output-

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.

Example

Output-