The this Keyword
What Does this Refer To?
Inside any non-static method or constructor, this is a reference to the current object — the specific instance the method was called on. It lets an object refer to itself explicitly, which is especially useful for resolving naming conflicts and for chaining constructors or method calls.
Resolving Field vs. Parameter Shadowing
A very common pattern is naming a constructor or setter parameter exactly the same as the field it initializes. Inside that method, the plain name refers to the parameter (the parameter shadows the field — see the variable scope page for the general rule). Writing this.fieldName instead unambiguously reaches the instance field.
Using this to disambiguate a shadowed field
public class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name; // this.name = the field, name = the parameter
this.age = age;
}
void printInfo() {
System.out.println(name + " is " + age + " years old");
}
public static void main(String[] args) {
Person p = new Person("Sana", 29);
p.printInfo();
}
}Sana is 29 years old
Constructor Chaining with this(...)
As covered on the constructors page, this(...) — with parentheses and arguments — calls another constructor in the same class. It must be the first statement in the calling constructor, and it's the standard way to avoid duplicating setup logic across overloaded constructors.
Quick recap of this(...) chaining
public class Box {
int width;
int height;
Box(int width, int height) {
this.width = width;
this.height = height;
}
Box(int side) {
this(side, side); // chains to the constructor above
}
}Returning this for Method Chaining
A method can return this to hand back a reference to the current object, allowing the caller to chain multiple method calls together in a single expression. This pattern is called a fluent interface, and it's common in builder-style APIs.
A fluent PizzaBuilder
public class PizzaBuilder {
private StringBuilder toppings = new StringBuilder();
private String size = "medium";
PizzaBuilder withSize(String size) {
this.size = size;
return this; // return the current object to allow chaining
}
PizzaBuilder addTopping(String topping) {
if (toppings.length() > 0) {
toppings.append(", ");
}
toppings.append(topping);
return this; // return the current object to allow chaining
}
void printOrder() {
System.out.println(size + " pizza with " + toppings);
}
public static void main(String[] args) {
new PizzaBuilder()
.withSize("large")
.addTopping("mushrooms")
.addTopping("olives")
.printOrder(); // one chained expression
}
}large pizza with mushrooms, olives
this always refers to the object the current method or constructor was invoked on
Use this.field to reach a field that a parameter or local variable is shadowing
Use this(...) at the start of a constructor to chain to another constructor in the same class
Return this from a method to enable fluent, chainable method calls