Explain the purpose of the this keyword in Java.
The this keyword in Java is a reference variable that refers to the current object of a class. It is primarily used in the following scenarios:
To Resolve Ambiguity Between Instance Variables and Parameters
When instance variables and method parameters have the same name, this helps differentiate between them.
class Example {
int x;
Example(int x) {
this.x = x; // Refers to the instance variable x
}
}
To Call Another Constructor in the Same Class
It is used to call one constructor from another constructor within the same class. This is called constructor chaining.
To Pass the Current Object as an Argument
The this keyword can pass the current object as a parameter to a method or constructor.
void display(Example obj) { … }
display(this);
To Return the Current Object
The this keyword can return the current object from a method.
Example getObject() {
return this;
}
To Access the Current Object’s Members
It is used to access instance variables, methods, or constructors from within the same object.