this keyword in Java
this keyword is used to refer the current object.
this keyword can be used for referencing
- instance variables of objects.
- instance methods of objects.
this keyword for instance variables
Instance variables can be referenced using this keyword.
Example 1
class ThisVariableTest{
int data;
void assign(int i){
this.data=i;
System.out.println("Value of 'data' variable is "+this.data);
}
public static void main(String args[]){
ThisVariableTest tvt=new ThisVariableTest();
tvt.assign(5);
}
}
Try In EditorOutput
Value of 'data' variable is 5
To differentiate a instance variable from a local variable we can use this keyword.
Example 2
class ThisVariableTest2{
int data;
void assign(int data){
this.data=data;
System.out.println("Value of 'data' variable is "+this.data);
}
public static void main(String args[]){
ThisVariableTest2 tvt=new ThisVariableTest2();
tvt.assign(5);
}
}
Try In EditorOutput
Value of 'data' variable is 5
this keyword for instance methods
Instance methods can be referenced using this keyword.
this keyword can be used to reference the method of current object.
Example
class ThisMethodTest{
void assign(int i){
this.square(i);
}
void square(int i){
System.out.println("Square of the value is "+i*i);
}
public static void main(String args[]){
ThisMethodTest tvt=new ThisMethodTest();
tvt.assign(5);
}
}
Try In EditorOutput
Square of the value is 25
We can also use Class_name.this to refer the current object for a specific class. For example, we can use ThisMethodTest.this.assign(i) instead of this.assign(i) in the above program. This will be explained fully in inner classes.