this keyword

What is this
this is a keyword in Java. Which can be used inside method or constructor of class. It(this) works as a reference to current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor.

this keyword with field(Instance Variable)
this keyword can be very useful in case of Variable Hiding. We can not create two Instance/Local Variable with same name. But it is legal to create One Instance Variable & One Local Variable or Method parameter with same name. In this scenario Local Variable will hide the Instance Variable which is called Variable Hiding.

Example of Variable Hiding

Output of the above programme

As you can Instance Variable is hiding here and value getting displayed is the value of Local Variable(or Method Parameter) and not Instance Variable. To solve this problem this keyword can be used with field to point Instance Variable instead of Local Variable.

Example of this keyword for Variable Hiding

Output of the above programme

this keyword with Constructor
this keyword can be used inside Constructor to call another overloaded Constructor in same class. It is called Explicit Constructor Invocation. If a class has two overloaded constructor one without argument and another with argument. Then this keyword can be used to call Constructor with argument from Constructor without argument. As constructor can not be called explicitly.

Example of this with Constructor

Output of above programme

As you can see this can be used to invoke overloaded constructor in the same class.


this keyword can only be the first statement in Constructor.
A constructor can have either this or super keyword but not both.
this keyword with Method
this keyword can also be used inside methods to call another method from same class.

Example of this keyword with Method

Output of above programme

Example of this keyword as method parameter