Method Chaining in Java
In Java, method chaining is the chain of methods being called one after another. It is the same as constructor chaining but the only difference is of method and constructor. In this section, we will discuss the method chaining in Java.
Method chaining is a common syntax to invoke multiple methods calls in OOPs. Each method in chaining returns an object. It violates the need of 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. For example,
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.
It 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.
Applications of Method Chaining
Invoking Methods Without Method Chaining
The following Java program does not implement the method-changing concept.
The product name is AC. It's cost is 20000. Available quantity is 4
Invoking Methods with Method Chaining
Student Detail is: Id: 1183 Name: Herry Tangri Age: 17 Standard: 9
Let's see another example.
In the above program, the statement myNumber.add(5).print(); can also be written as follows:
We can also call any number of add() methods.