Careeroza
The this Keyword
What this Means
Inside an instance method or constructor, this is a reference to the current object, the object on which the method was called.
| Use | Example | Why |
|---|---|---|
| Separate field from parameter | this.name = name; | parameter hides the field with the same name |
| Call another constructor | this("Guest"); | reuse constructor code |
| Pass the current object | cart.add(this); | give other code a reference to yourself |
| Return the current object | return this; | method chaining (fluent style) |
Field vs Parameter
Example
Without this, the statement name = name just assigns the parameter to itself and the field stays null.
public class Main {
public static void main(String[] args) {
System.out.println(new Wrong("Asha").name);
System.out.println(new Right("Asha").name);
}
}
class Wrong {
String name;
Wrong(String name) {
name = name; // assigns the parameter to itself
}
}
class Right {
String name;
Right(String name) {
this.name = name; // field = parameter
}
}Output
null Asha
Method Chaining with return this
Example
Returning this lets callers chain calls in one expression. Builders in many libraries work this way.
public class Main {
public static void main(String[] args) {
Order order = new Order()
.addItem("Biryani", 250)
.addItem("Lassi", 60)
.applyCoupon(50);
System.out.println("Total: Rs " + order.total);
}
}
class Order {
int total;
Order addItem(String name, int price) {
System.out.println("Added " + name);
total += price;
return this;
}
Order applyCoupon(int discount) {
total -= discount;
return this;
}
}Output
Added Biryani Added Lassi Total: Rs 260