How does chained methods execute in java?

前端 未结 3 1714
清酒与你
清酒与你 2020-12-20 06:29

Here is my code :

result = method1().method2().method3();

I would like to know the execution hierarchy of the above code/

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 07:07

    Just go through the following points.

    1. Determine what the leftmost method call will return (let’s call it x).
    2. Use x as the object invoking the second (from the left) method. If there are only two chained methods, the result of the second method call is the expression's result.
    3. If there is a third method, the result of the second method call is used to invoke the third method.

    As per your statement, the execution hierarchy will be as follows:

    1. First , method1() which is the leftmost method will be called.
    2. Suppose method1() returns an object "meth" then the second method (from the left) method2() will be called as meth.method2().
    3. Last, the object returned from method2() will be used to call the method3().

    Hope it clarifies you doubt.

提交回复
热议问题