What does the this keyword mean in Java, and where do you use it?
this is a reference to the current object, the one whose method or constructor is running. It is used to separate fields from parameters of the same name, to call another constructor, and to pass the current object along.
Explain it simply
When you say "my phone" you mean the phone of whoever is speaking. Inside a method, this works the same way: it points to the object that was used to call the method.
Three common uses: (1) this.name = name tells the compiler the left side is the field and the right side is the parameter; (2) this(...) calls another constructor of the same class; (3) return this or list.add(this) hands the current object to someone else.
Example
class Account {
private String owner;
private double balance;
Account(String owner) { this(owner, 0); } // calls the other constructor
Account(String owner, double balance) {
this.owner = owner; // field = parameter
this.balance = balance;
}
Account deposit(double amt) {
balance += amt;
return this; // allows chaining
}
}
new Account("Meera").deposit(500).deposit(250);this(...) must be the first statement in the constructor. this does not exist in static methods because no object is involved.
What to say in the interview
"this is the implicit reference to the current object. I use it to resolve name clashes between a field and a parameter, to chain constructors with this(...), and to return the object for method chaining. It is unavailable in static context."
Common mistakes
- Writing
name = namein a constructor. That assigns the parameter to itself and leaves the field at its default. - Trying to use this inside a static method.