Method Chaining
In many libraries, you see a large number of .
(dot) notations (like in chains) calling several functions sequentially. This is a programming style named method chaining. In method chaining, most of the methods in a class return the object itself so another function can use the object later on.

For example, suppose you want to create a group of shapes with a new class ShapeGroup
that will contain several shapes inside its internal data structure. We will implement several methods to add different types of shapes to our class. Each of these methods in our ShapeGroup
class will return itself in order to use method chaining.
TEXT/X-JAVA
1public class ShapeGroup {
2 private List<Shape> arrayList;
3 private List<Integer> labels; // 1 = Rectangle, 2 = Circle, 3 = Square
4
5 public ShapeGroup() {
6 arrayList = new ArrayList<>();
7 labels = new ArrayList<>();
8 }
9
10 // These methods will return itself, ShapeGroup
11 public ShapeGroup addRect(Rectangle rect) {
12 arrayList.add(rect);
13 labels.add(1);
14 return this;
15 }
16
17 public ShapeGroup addRect(int height, int width) {
18 return this.addRect(new Rectangle(height, width));
19 }
20
21 public ShapeGroup addCircle(Circle circle) {
22 arrayList.add(circle);
23 labels.add(2);
24 return this;
25 }
26
27 public ShapeGroup addCircle(double radius) {
28 return this.addCircle(new Circle(radius));
29 }
30
31 public ShapeGroup addSquare(Square sq) {
32 arrayList.add(sq);
33 labels.add(3);
34 return this;
35 }
36
37 public ShapeGroup addSquare(int side) {
38 return this.addSquare(new Square(side));
39 }
40}
Inside the main
method, we can add
a bunch of shapes with only 1 line of code.
TEXT/X-JAVA
1public class Main {
2 public static void main(String[] args) {
3 ShapeGroup sg = new ShapeGroup();
4 // Adding 5 shapes
5 sg.addSquare(5).addRect(5,4).addCircle(new Circle(3.4)).addCircle(3.4).addRect(new Rectangle(8,2));
6 }
7}