Page 294 - Introduction to Programming with Java: A Problem Solving Approach
P. 294
260 Chapter 7 Object-Oriented Programming—Additional Details 7.6 Method-Call Chaining
At this point, you should be fairly comfortable with calling a method. Now it’s time to go one step further. In this section, you learn to call several methods in succession, all within one statement. That’s called method-call chaining, and it can lead to more compact and more elegant code.
If you look back at Figures 7.3 and 7.4, you’ll see several instances where we call several methods one after another, and we use a separate statement for each successive method call, like this code fragment from Figure 7.4:
nathanCar.setMake("Audi");
nathanCar.setYear(1998);
Wouldn’t it be nice to be able to chain the method calls together like this?
nathanCar.setMake("Audi").setYear(1998);
Method-call chaining is an option, not a requirement. So why use it? Because it can often lead to more elegant code—more compact and easier to understand.
Let’s look at method-call chaining in the context of a complete program. See the method-call chain (indicated by a callout) in Figure 7.8’s Car3Driver class. Left-to-right precedence applies, so car.setMake executes first. The setMake method returns the calling object, which is the car object at the left of car.setMake. The returned car object is then used to call the setYear method. The setYear method calls the printIt method in a similar fashion.
Method call chaining doesn’t work by default. If you want to enable method-call chaining for methods
Apago PDF Enhancer
from the same class, you need the following two items in each method definition:
1. The last line in the method body should return the calling object by specifying return this; 2. In the method heading, the return type should be the method’s class name.
/***************************************************************
*
Car3Driver.java
Dean & Dean
This drives Car3 to illustrate method-call chaining.
***************************************************************/
*
*
*
public class Car3Driver
{
}
public static void main(String[] args)
{
Car3 car = new Car3();
Usedotstochaintogethermethodcalls.
car.setMake("Honda").setYear(1998).printIt();
} // end main
// end class Car3Driver
Figure 7.8
Car3 program driver which illustrates method-call chaining