JaVa
   

Invocation Chaining

Invocation chaining means that you are not limited to merely accessing one class/object member in a given statement with the . operator but may continue to access further members in a given statement. For example, let's say that we wanted to convert an integer value to a String object representation and then retrieve the first digit from the string as a character. We might perform this task as follows:

int i = 72;
String str = String.valueOf(i);
char firstChar = str.charAt(0);
System.out.println(firstChar); // prints 7


This code is perfectly fine, but we could have also implemented this code in a neater fashion using invocation chaining as follows.

int i = 72;
char firstChar = String.valueOf(i).charAt(0);
System.out.println(firstChar); // prints 7 also


It's quite easy to see how this works. The . operator has a left (left to right) precedence, as seen in the operator precedence table in . With this in mind, we can see that the following statement is evaluated first of all:

String.valueOf(i)


This will return a new String object representation of the integer variable i passed to it. Then the method charAt is invoked on the new String object, returning the first character in the string to the variable firstChar. You should look at the statement String.valueOf(i) as a reference to the String object itself, which it is, as this is what the method returns. You can then access members of the String object like charAt that we accessed. If we said that we had a Person object inside a Planet object that in turn was inside a SolarSystem object, and the SolarSystem object was inside a Universe object, we may access the Person object from a reference to the Universe object as follows.

Person bob = myUniverse.mySolarSystem.myPlanet.myPerson;


JaVa
   
Comments