this Keyword in Java

this keyword in Java is the reference to the current object. To make it clearer, when you invoke any method (or constructor at the time of object creation), using an object of the class then this keyword is the reference to the object used to call the method.

For example-

Output

In the example using the class object a method is called and from that method this is returned. Since this is a reference to the current object that is why on comparing the object references those are equal.

How to use this keyword in Java

this keyword in Java can be used in many scenarios.

  1. To resolve name space collision between instance and local variable.
  2. To call one constructor from another in case of constructor overloading.
  3. To call any method.
  4. To pass as an argument when object has to be passed.

Using this to access instance variables

Generally in case of constructors it is a common practice to give the local variables with in the constructor same name as the instance variables. In that case local variables hide the instance variables and local variables take precedence over instance variables with in the context of that constructor. Since this is a reference to the object itself so this keyword can be used to access instance variables in such scenario.

As you can see in the example code, constructor has the local variables with the same name as the instance variables and this is used to resolve the conflict.

Using this to call overloaded constructors

You can use this to call one constructor from another in case of overloaded constructor so that only one of the constructor actually do the initialization.

In the example you can see that the initialization is ultimately done by the following constructor-

All the other constructors are using this keyword to form a chain to call the constructor where initialization is finally done.

Using this keyword to call any method

Since this is the reference to the current object so this can also be used to call the methods of the class.

Output

this can be passed as an argument when object has to be passed

Since this is the reference to the current object so you can pass this as an argument where object needs to be passed.

That’s all for the topic this Keyword in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.