this keyword is used to refer to the object on which a method was invoked.
Take a look at the following code which contains a single instance variable x and a method setX().
Now, to understand what this.x means, we use the following code
3 | public static void main(String[] args) { |
4 | MyNumber myNumber1 = new MyNumber(); |
The method setX() was called on the object myNumber1. Within setX(), the statement this.x=3 will be executed. As we said in the beginning of this article, ‘this refers to the object on which a method was invoked’. Here, we have invoked the method setX() on the object myNumber1. So, this will refer to the object myNumber1. So,
this.x = 3 ;
will be interpreted as
myNumber1.x = 3
which will set x to 3.
We could written the above program without using this keyword in the following way.
The output will still be the same.
Now, you might ask what is the use of this keyword if we can achieve the same thing without using it.
Consider the following example:
The method printX() will print 4 and not 3. This is because when we declare a variable in a method with the same name as that of another instance variable, then when we refer to that variable within the method, we get access to the variable defined in the method and not the instance variable of the class. This is illustrated in the following diagram:
If we want to access the instance variable, we do it with this.x.
8 | System.out.printn( this .x); |
The above program will print,
To see why the second line printed 3, let us use the first line in this article – ‘this refers to the object on which the method was invoked’.
1 | MyNumber myNumber1 = new MyNumber(); |
The method printX() was invoked on the object MyNumber1. So, this will refer to myNumber1 and this.x will be myNumber1.x which is 3.
Normally, we use the ‘this’ keyword in constructors and set methods so that we can use the same name for instance variables and formal parameters.
Here is an example program with the keyword this used in a constructor and two set methods.
6 | public Student( int rollNumber, int marks) { |
7 | this .rollNumber = rollNumber; |
11 | public void setRollNumber( int rollNumber) { |
12 | this .rollNumber = rollNumber; |
15 | public void setMarks( int marks) { |