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
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
- It is used to implement method cascading.
- It is also used to implement in fluent interfaces.
Invoking Methods Without Method Chaining
The following Java program does not implement the method-changing concept.
Product.java
Output:
The product name is AC. It's cost is 20000. Available quantity is 4
Invoking Methods with Method Chaining
Student.java
Output:
Student Detail is:
Id: 1183
Name: Herry Tangri
Age: 17
Standard: 9
Let's see another example.
DomNumber.java
MethodChaining.java
Output:
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.
You may be interested in:
>> Is a Chromebook worth replacing a Windows laptop?
>> Find out in detail the outstanding features of Google Pixel 4a
>> Top 7 best earbuds you should not miss
Related Posts:
>> Recognizing 12 Basic Body Shapes To Choose Better Clothes
>>Ranking the 10 most used smart technology devices
>> Top 5+ Best E-readers: Compact & Convenient Pen
0 Comments:
Post a Comment