Java this keyword
There can be a lot of usage of this keyword. In java this is a reference variable that refers to the current object.
Consider the following source code:
public static void main(String args)
int x, y; //instance variables
Test(int x, int y) // local variables
Here the instance and local variables are same. To differentiate which is instance variables and which is local variables, we use the keyword this. So the keyword this refers to the current object.
So this.x and this.y refers to instance variable
Uses of this keyword:
- this keyword can be used to refer current class instance variable.
- this( ) can be used to invoke current class constructor.
- this( ) can be used to invoke current class method(implicitly).
- this can be passed as argument in the method call.
- this can be passed as argument in the constructor call.
- this keyword can also be used to return the current class instance.