Below is a sample class (CustomList.class, which extends ArrayList):
In the above class, you can see the custom 'addElem' method, which returns the Object itself (this), thus allowing it for 'Method Chaining'. Below is the 'Fluent Interface Demo' class:
In the above class, you can see the difference between how you add elements to 'arrList' (ArrayList) and 'custList' (CustonList). That's Syntactic Sugar for you! :)
You can see this kind of implementation, in a couple of Java classes (Like StringBuffer, StringBuilder, BigDecimal, et al). Below is an example of Method Chaining, using Java's BigDecimal:
And below is an example of using Java's StringBuilder, which shows 'Method Chaining':
Reference: JQuery Method Chaining<
There are also a couple of DSL's which are specially built, using this concept of 'Fluent Interface'.
Op4j is one interesting framework among 'em. Below is example code for Op4j:
Reference: Op4j (You can find more interesting examples in the referenced source).
The views expressed on this blog are my personal views and do not reflect the views of
my employer or campaigns I am supporting.
All sample code is provided for illustrative purposes only. These examples have not been thoroughly tested under all conditions. The writer therefore, cannot guarantee or imply reliability, serviceability, or function of these programs.
All programs contained herein are provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.