Reputation: 41
Can anybody explain this how this line of code works:
Rational sum = a.add(b).add(c);
I don't understand how object b (which is an argument) is receiving a method?
Upvotes: 1
Views: 3459
Reputation: 49372
This is called method chaining. The method add()
actually returns a reference of the currently modified object or a new object of the same type on which the method was invoked. Say suppose the object referred to by a
is a BigInteger , when you invoke a.add(b) , it returns a BigInteger
object whose value is a+b
, and hence you can invoke .add(c)
on that object again.
Rational sum = a.add(b).add(c);
// is equivalent to
Rational temp = a.add(b);
Rational sum = temp.add(c);
Method chaining is not required. It only potentially improves readability and reduces the amount of source code. It is the core concept behind building a fluent interface.
A sample illustration:
This practice is used mostly in Builder pattern, you can find this pattern in API itself in StringBuilder class.
I don't understand how object b (which is an argument) is receiving a method?
No your understanding is wrong , a.add(b)
means you are invoking method add()
on object a
and passing it a reference of object b
. The resultant object which the method a.add(b)
returns is of the same type as a
, and then in succession you call the method .add(c)
on the returned object passing a reference of object c
to that method.
Upvotes: 4
Reputation: 121998
Each method in the chain has to return a class or an interface. The next method in the chain has to be a part of the returned class.
in your case a.add(b)
returning some calss/interface and then calling add(c)
on that and that method returns your sum
Upvotes: 1