官术网_书友最值得收藏!

Method call chaining

OOP affords us the opportunity to use method call chaining. That is the process of making multiple method calls in a single statement. Here is the syntax:

object.method1().method2().method3().method4();

Using the syntax provided previously, we can walk through the process of method call chaining. The object first calls method1(), which returns the calling object. Next, that returned object calls method2(), which returns the calling object. You can see the process here. It works from left to right.

So, we can implement this in our Driver class, as shown here:

// Example using method call chaining
Bicycle myBike5 = new Bicycle(24, 418.50, 17.2, "Green");
myBike5.setColor("Peach").setGears(32).outputData("Number 5");

Before this code can work, we will need to make two changes to each method we want to use in our method call chaining:

  • Add a return type to the method definition
  • Add a return this; statement to each method

Here is an example of the setGears() method that the preceding changes listed made:

public Bicycle setGears(int nbr) {
this.gears = nbr;
return this;
}

Once these changes are made, we can run the Driver class:

Method call chaining execution results

The preceding screenshot shows the final result.

主站蜘蛛池模板: 荣昌县| 化州市| 潼南县| 大姚县| 剑阁县| 荣昌县| 厦门市| 杭锦旗| 碌曲县| 武功县| 阳山县| 平南县| 武川县| 台北市| 紫金县| 青田县| 徐闻县| 邮箱| 自治县| 泰兴市| 武功县| 怀仁县| 浦北县| 镇雄县| 湖州市| 望谟县| 固安县| 彭山县| 游戏| 武汉市| 白河县| 澄迈县| 孝昌县| 浦县| 轮台县| 大城县| 石家庄市| 乌拉特前旗| 福海县| 津南区| 林甸县|