Open In App

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.



Syntax:

obj.method1().method2().method3();  

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.

Example 1: 




class A {
 
    private int a;
    private float b;
 
    A() { System.out.println("Calling The Constructor"); }
 
    int setint(int a)
    {
        this.a = a;
        return this.a;
    }
 
    float setfloat(float b)
    {
        this.b = b;
        return this.b;
    }
 
    void display()
    {
        System.out.println("Display=" + a + " " + b);
    }
}
 
// Driver code
public class Example {
    public static void main(String[] args)
    {
        // This will return an error as
        // display() method needs an object but
        // setint(10) is returning an int value
        // instead of an object reference
        new A().setint(10).display();
    }
}

Compilation Error in the Java code:

prog.java:34: error: int cannot be dereferenced
        new A().setint(10).display();
                          ^
1 error

Explanation:

Example 2:




class A {
 
    private int a;
    private float b;
 
    A() { System.out.println("Calling The Constructor"); }
 
    public A setint(int a)
    {
        this.a = a;
        return this;
    }
 
    public A setfloat(float b)
    {
        this.b = b;
        return this;
    }
 
    void display()
    {
        System.out.println("Display=" + a + " " + b);
    }
}
 
// Driver code
public class Example {
    public static void main(String[] args)
    {
        // This is the "method chaining".
        new A().setint(10).setfloat(20).display();
    }
}

Output
Calling The Constructor
Display=10 20.0

Article Tags :