How does chained methods execute in java?

早过忘川 提交于 2019-12-04 02:22:06

问题


Here is my code :

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

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


回答1:


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.




回答2:


I'm explaining hierarchy of the above code with small example.

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

Example:

getYear().toString().trim(); //like method1().method2().method3()

First will be execute get year() which returns a Integer:

2016.toString().trim();

Secound will be execute toString() method of integer class which returns an string:

"2016".trim();

In Last trimming the stringwith trim() method of string class.




回答3:


Same as this:

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


来源:https://stackoverflow.com/questions/35932711/how-does-chained-methods-execute-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!