Page 295 - Introduction to Programming with Java: A Problem Solving Approach
P. 295

                We’ve implemented those items in the Car3 class in Figure 7.9. Verify that setMake and setYear are enabled properly for method-call chaining. Specifically, verify that (1) the last line in each method body is return this;,and(2)ineachmethodheading,thereturntypeisthemethod’sclassname,Car3.
Wheneveryoufinishamethodwithareturn this;statement,you’remakingitpossibletousethe same object to call the next method in the chain. However, you can also chain methods called by differ- ent types of objects. Just arrange the chain so that the reference type returned by each preceding method matches the class of each following method. So, in general, to make a method chainable, do these two things:
1. In the method heading, specify the return type as the class of a potential following method.
2. Finish the method body with:
return <reference-to-object-that-will-call-the-following-method>;
7.6 Method-Call Chaining 261
 /**********************************************************
*
Car3.java
Dean & Dean
This class illustrates methods that can be chained.
**********************************************************/
*
*
*
public class Car3
{
private StringApmaakeg;oPDFEnhancer private int year;
//************************************
public Car3 setMake(String make)
     }
// end class Car3
{
this.make = make;
return this;
// end setMake
public Car3 setYear(int year)
Return the calling object.
   }
{
}
this.year = year;
return this;
// end setYear
//*******************************************************
public void printIt()
{
System.out.println(make + ", " + year);
} // end printIt
*******************
The return type is the same as the class name.
Figure 7.9
Car3 class
























































   293   294   295   296   297