Use of this keyword in java with example

Use of this keyword in java

this is a keyword in Java and is a reference to the current object(the object which invoked the method or constructor). Since this is a reference to an object, it cannot be used in a static context(inside static methods or static initialization blocks). In this article we will see the use of this keyword in Java with examples.

1. It should be used explicitly to refer to instance variables of an object if the instance variable and local variable names are same. For example,

In the above example, the constructor is used to assign values to instance variables name and age. Since the argument names are same as the instance variable names, this should be used explicitly to refer to instance variable. If you don’t use this keyword here, the value will  be assigned to the arguments itself.

2. this can be used to call constructors within same class

From within a constructor, this keyword can be used to call another constructor in the same class. This is called an explicit constructor invocation. If used then it must be the first statement in the constructor. Here is an example,

3. this is a final variable in Java and you cannot assign a value to it. Doing so will result in compile time error showing “The left-hand side of an assignment must be a variable”.

4. this keyword can be used to call non-static methods in the class.

Here is an example.

5.this can be used as a return value from non-static methods

Here is an example.

6. this can be passed as method parameter

Here is an example.

this can also be used to refer static members in a class but it is not recommended to use because this refers to current object and static members are not associated with a particular object.

That’s all about the use of this keyword in Java. Hope you find the article useful.

 

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

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