When and how to Use "return this" in Java

amolocaleb :

I'm developing a simple java project to help me master the language and was researching on method chaining when I came across the return this statement. I'm not quite sure of its use cases apart from method chaining and what it means exactly to return this. Its documentation was obviously not written for newbies. Could someone help make it clearer?

Bohemian :
return this;

returns the instance itself from the method.

Returning the instance is usually (but not always) used when implementing a fluent interface, which allows code to look like this:

myObj.method1().method2().method3();

This in turn is very commonly used (but not required) when implementing the builder pattern.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471462&siteId=1