The this keyword in Java is a reference to the current object of a class. It is commonly used to access instance variables, invoke methods of the current object, and resolve naming conflicts between instance variables and method parameters.
Key Points
this refers to the current object instance.
It is used to distinguish instance variables from local variables or method parameters with the same name.
It can be used to invoke another constructor within the same class using this().
It can be passed as an argument to methods or constructors.
It can be returned from a method to return the current object.
Example
When a constructor parameter has the same name as an instance variable, the this keyword helps differentiate between them.
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public void display() {
System.out.println(this.name);
}
}
Common Mistakes
Using this inside a static method, which does not compile because there is no current object.
Forgetting this in a constructor when the parameter has the same name as the field, so the field is never assigned (name = name only reassigns the parameter).
Follow-up Questions
What does this() do? It calls another constructor of the same class and must be the first statement in the constructor.
Can you return this? Yes. Returning this enables method chaining, as in the Builder pattern.
Interview Tip
A concise interview answer is
The this keyword is a reference to the current object. It is mainly used to access instance variables, call current class methods or constructors, resolve variable naming conflicts, and refer to the current object within a class.