this keyword is a reference to the current object of the class. it is used to resolve ambiguity between instance variables and parameters or to invoke methods/constructors of the current class.
referring to instance variable
class Person Person {
String name;
int age;
Person(String name, int age) {
this.name = name; // 'this.name' refers to the instance variable, 'name' to the parameter
this.age = age;
}
}
invoking another constructor
class Person {
String name;
int age;
Person(String name) {
this(name, 0); // Calls the constructor with two parameters
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
returning to current object
class Person {
String name;
int age;
Person setName(String name) {
this.name = name;
return this; // Returns the current object
}
Person setAge(int age) {
this.age = age;
return this;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Alice").setAge(25); // Method chaining
}
}
passing the current object to a method
class Person {
String name;
void display(Person person) {
System.out.println("Person's name: " + person.name);
}
void show() {
display(this); // Passes the current object
}
}
- usage of
thiskeyword is not allowed in static blocks or methods because they belong to the class rather than the instance. - improved code readability and prevent errors due to naming conflicts
- it is commonly used in constructors, getters and setters.