this KeywordThe this keyword in Java refers to the current object. It is commonly used to remove ambiguity between instance variables and parameters, call current class methods, and invoke constructors.
this refers to the current class objectWhen local variables (method parameters) have the same name as instance variables, Java gives priority to local variables. The this keyword explicitly refers to instance variables of the current object.
// Using this keyword to distinguish instance variables
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println(id + " " + name);
}
}
The constructor parameters id and name have the same names as instance variables. Using this.id and this.name ensures the instance variables are correctly initialized.
Type in the boxes below to see how this bridges the constructor inputs to the object memory.
this when parameter names match instance variablesEmployee with fields and a constructor using thisthisthis()