thisrefers to the current object.Main Uses of
thisResolve Variable Shadowing. When a constructor or setter parameter has the exact same name as an instance variable,
this.variabletells Java you mean the object's field rather than the local parameter.Constructor Chaining (
this()). You can call one overloaded constructor from another inside the same class usingthis(...)to avoid duplicating initialization code.Pass the Current Object as an Argument.
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println("ID: " + this.id);
System.out.println("Name: " + this.name);
}
public static void main(String[] args) {
Student s = new Student(101, "Geeks");
s.display();
}
}