Unit 3 Cycle 2 Day 4: this Keyword for Method Chaining
Share
this Keyword for Method Chaining
Section 3.10 — The this Keyword
Key Concept
The this keyword can enable method chaining by having mutator methods return this instead of void. While not required on the AP exam, understanding that this is a reference to the current object helps explain patterns like obj.setName("A").setAge(25) where each method returns the same object for the next call. On the exam, this is more commonly tested in constructors for disambiguation and in methods that pass the current object as an argument to another method.
Consider the following class.
What does new Builder().add("A").add("B").add("C").build() return?
Answer: (B) "ABC"
Each add() appends to text and returns this. add("A"): text="A". add("B"): text="AB". add("C"): text="ABC". build() returns "ABC".
Why Not the Others?
(A) Each add appends to the existing text, not replaces it.
(C) Only the last add adds "C", but previous adds are preserved.
(D) Returning this enables method chaining. Each call returns the same Builder object.
Common Mistake
Method chaining works because return this gives back the same object. Each subsequent call operates on the same object, accumulating changes.
AP Exam Tip
The Builder pattern uses method chaining. return this allows fluent API calls. Trace the state of the object after each chained call.