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 Chapter 2. 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 1.4 Game Programming
Java 1.4 Game Programming (Wordware Game and Graphics Library)
ISBN: 1556229631
EAN: 2147483647
Year: 2003
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net