this keyword in java with example

this keyword in java is used to refer to current object or instance of class. It can be used in the constructor to call any other overloaded constructor but this keyword should be the first statement in the constructor.

This keyword can be used for instance variables

this keyword can be used to refer to the instance variable of class.

When you run above program, you will get below output:

Employee’s name : John
Employee’s age : 20

As you can see we have used this keyword to set values for instance variable in the constructor.

This keyword can be used to call the overloaded constructor

If you want to call overloaded constructor of same class, you can use this keyword to do that.
For example:

When you run above program, you will get below output:

Calling No arg constructor
Calling Parameterized constructor
Employee’s name : John
Employee’s age : 20

Please note that this keyword used for calling another constructor should be first statement in that constructor.

this keyword can be used return object of the class

Calling No arg constructor
Employee’s name : John
Employee’s age : 20

that’s all about this keyword in java.

Was this post helpful?

Leave a Reply

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