The this keyword in Java is used when a method has to refer to an object that has invoked it. It can be used inside any method to refer to the current object. This means that this is always used as a reference to the object on which the method was invoked. We can use this anywhere as reference to an object of the current class type is permitted.
Following are the usage of java this keyword.
• this() is a reference variable that refers to the current object.
• this() can be used to refer instance variable of current class.
• this() can be used to invoke current class constructor.
• this() can be passed as an argument in the method call.
• this() can be passed as argument in the constructor call.
• this() can be used to return the current class instance from the method.
Program illustrates the use of the java this keyword. In the program, the main() method creates an object ob of class CircleEx. In the method CircleEx, this.x refers to the first passed value, that is, 10. Similarly this.y and this.radius refers to the second and third values passed to the method CircleEx, respectively (20 and 10). The method display in this program displays the values of x, y and radius when this.display() is invoked from the method CircleEx .
Illustrating the use of the keyword this.
public dass CirdeEx {
int x,y,radius;
public CircleEx(int x, int y, int radius) {
this.x = x;
this.y =y;
this.radius = radius;
this.display();
}
void display() {
System.out.println(“value of x is” +x);
System.out.println(“value of x is” +y);
System.out.println(“value of x is” +radius);
}
public static void main(String arg[ ]) {
System.out.println(“Use of keyword this”);
CircleEx ob = new CirdeEx(10, 20, 10);
}
}
The output of Program is as shown below:
Use of keyword this
value of x is 10
value of x is 20
value of x is 10
In most programs, this can be omitted entirely. Programmers can refer to both instance variables and method calls defined in the current class simply by invoking their name, this is implicit in those references. This is shown below:
t = x // the x instance variable for this object
myMethod(this) // call the myMethod method. Defined in this class
The keyword this is a reference to the current instance of a class. It should be used only within the body of an instance method definition. Class methods (methods declared with the keyword static) cannot use this.