Javatpoint Logo
Javatpoint Logo

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

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:

6

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.


Next TopicOrphaned Case Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA