Returning this for Method Chaining
What you'll learn: How returning this from your methods creates elegant, fluent APIs that let you chain multiple method calls in one line.
The Core Idea
When a method returns this (a reference to the current object), you can immediately call another method on that same object. This creates a chain: obj.setX(5).setY(10).setZ(15). Instead of writing three separate statements, you write one smooth, readable expression.
Think of it like passing a baton in a relay race—each method does its job and immediately hands the object to the next method.
Why Return this?
Normally, setter methods are void—they change the object but return nothing. By returning this instead, you enable chaining:
Without chaining:
Rectangle rect = new Rectangle();
rect.setWidth(100);
rect.setHeight(50);
rect.setColor("blue");
With chaining:
Rectangle rect = new Rectangle()
.setWidth(100)
.setHeight(50)
.setColor("blue");
How It Works
Each method modifies the object, then returns this so the next method call operates on the same object:
public class Rectangle {
private int width;
private int height;
public Rectangle setWidth(int width) {
this.width = width;
return this; // Return the current object
}
public Rectangle setHeight(int height) {
this.height = height;
return this; // Enable chaining
}
}
The chain rect.setWidth(100).setHeight(50) works because setWidth returns rect, so you're effectively calling rect.setHeight(50) next.
Key Takeaway: Returning this from instance methods allows fluent, readable method chaining by passing the current object along the chain—each method modifies and returns the same object for the next call.