- Hands-On Design Patterns with Java
- Dr. Edward Lavieri
- 196字
- 2021-06-24 14:57:59
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:

The preceding screenshot shows the final result.
- 數據浪潮
- 數據庫技術與應用教程(Access)
- ETL數據整合與處理(Kettle)
- 使用GitOps實現Kubernetes的持續部署:模式、流程及工具
- 商業分析思維與實踐:用數據分析解決商業問題
- 揭秘云計算與大數據
- Sybase數據庫在UNIX、Windows上的實施和管理
- OracleDBA實戰攻略:運維管理、診斷優化、高可用與最佳實踐
- 數據庫原理與應用(Oracle版)
- 數據庫原理與設計(第2版)
- 數據庫技術及應用
- SAS金融數據挖掘與建模:系統方法與案例解析
- Unity 2018 By Example(Second Edition)
- 數據挖掘與數據化運營實戰:思路、方法、技巧與應用
- 數據會說話:活用數據表達、說服與決策