Method Chaining In Java with Examples
Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).
Method chaining in Java is a common syntax to invoke multiple methods calls in OOPs. Each method in chaining returns an object. It violates the need for intermediate variables. In other words, the method chaining can be defined as if we have an object and we call methods on that object one after another is called method chaining.
In the above statement, we have an object (obj) and calling method1() then method2(), after that the method3(). So, calling or invoking methods one after another is known as method chaining.
Note: Method chaining in Java is also known as parameter idiom or named parameter idiom. Sometimes it is also known as a train wreck because of the increase in the number of methods even though line breaks are often added between methods.
Let’s audit the example first, and then it will be much smoother to explain.
Compilation Error in the Java code:
prog.java:34: error: int cannot be dereferenced new A().setint(10).display(); ^ 1 error
- When we are calling the constructor, one should perceive that constructor does not hold any return type, but it returns the current object reference. Open this for more about constructors.
- As object reference is returned by the constructor, we can use the returned object reference for calling another method as well.
- Thus, by implementing the dot(.) operator, we can call another method, too, named “setint(10)”. As of now, we are trying to call the display method further, but, it’s impossible. Why? Check out the next point.
- Now, the “setint(10)” method returns the integer value of the variable. In a common way, one can easily understand that the next method can’t be called on the basis of a variable. To solve this, “setint(10)” method must return object reference. How it can be done?.
Calling The Constructor Display=10 20.0
- In the above example, we have derived setint(int a) & setfloat(float b) method as the class type.
- In this case, while returning, we are using “this,” and it is returning the current instance reference. Check this for the uses and values of “this” reference variable.
- When the method chaining is implemented in the main method, “setint(10)” & “setfloat(20)” are returning the object’s reference which is further used to call the “display()” method.