Method Chaining


As we discussed earlier in this chapter, an instance method is called on an object. Methods can also have a reference type as their return type. It is possible to use the return value of one method as the reference on which another is called. What's more, this operation can be performed in a single executable statement. This is called method chaining or cascading and is a way to call multiple methods successively.

Method chaining is provided as a convenience. While it can make your Java code more compact, it doesn't add any functionality and can make a code listing somewhat more difficult to follow. You don't have to chain methods, but the capability is there for you if you want it.

Example: Using Method Chaining

One way to convert a String to a primitive double type is to first convert the String to a Double object and then convert the Double object to a primitive double . The Double class provides the following two methods to achieve this goal ”

 public static Double valueOf(String str) public double doubleValue() 

The valueOf() method returns a Double object corresponding to the specified String . The doubleValue() method can then be called on the Double object returning a double value. Because the return value of valueOf() is the calling type of doubleValue() the method calls can be chained.

 public class ChainDemo {   public static void main(String args[]) {     //  You can convert the type in two steps     Double d = Double.valueOf("45.3");     double value = d.doubleValue();     value = value*3.0;     System.out.println("value is " + value);     //  Or you can chain the two steps together     value = Double.valueOf("45.3").doubleValue();     value = value*3.0;     System.out.println("value is " + value);   } } 

Output ”

 value is 135.9 value is 135.9 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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