this keyword in java

(Last Updated On: March 7, 2019)

Learn this keyword in java with programming uses and examples. – In java programs, this keyword is used in following scenarios in java programs.

  1. To refer current class fields(instance variables).
  2. To invoke the current class method.
  3. To invoke the current class constructor(implicitly).
  4. To pass as a current class object as a parameter in the methods.
  5. To pass a current class object in the constructor.
  6. To return the current class instance from the method

 

this keyword to refer current class fields

This keyword is used to refer class fields to avoid ambiguity between parameters in constructor or methods and class fields. For example; in below class constructor java code , if we don’t use this keyword then we don’t know if parameter is initialized to class field or class field is initialized to parameter.

 

If we use this keyword then it is clear indication that we are initializing class fields by constructor parameters.

 

Hiding variable Example:

If we have a local variable in a method having same name as field, then compiler will prefer local variable and hide the class field variable. If we want to use class field variable in the method then we must use this keyword before class field variable to access that.

 

Output:
dummy price 2000.0
Actual price 100000.0

If we don’t use this keyword before class field variable in the method displayPrice then the dummy price and actual price values will be same that is 2000.0

 

this keyword to refer current class method

This keyword can also be used in class method in java to improve readability. For example In below program we have used this keyword in highestPrice method to make the current object and incoming object in the parameter readable.


Output:

Honda is the car with highest price

 

Invoking current class constructor(implicitly) using this keyword.

Output:
Calculation completed
Add of three number is= 10
Add of three number is= 20
Add of three number is= 30

 

Passing an object as an argument through methods using this keyword.

Output:
data= 30

 

Passing object or an argument through constructor using this keyword.

Output:
data 10

 

Returning current class object using this.

Output:
studentObject: thiskeywordexample.Student@15db9742
studentObject: thiskeywordexample.Student@15db9742
name: sovan
age: 23