- 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.
- SQL Server 2012數(shù)據(jù)庫(kù)技術(shù)與應(yīng)用(微課版)
- Visual Studio 2015 Cookbook(Second Edition)
- Python數(shù)據(jù)分析、挖掘與可視化從入門到精通
- 分布式數(shù)據(jù)庫(kù)系統(tǒng):大數(shù)據(jù)時(shí)代新型數(shù)據(jù)庫(kù)技術(shù)(第3版)
- MySQL基礎(chǔ)教程
- 工業(yè)大數(shù)據(jù)分析算法實(shí)戰(zhàn)
- 深入淺出 Hyperscan:高性能正則表達(dá)式算法原理與設(shè)計(jì)
- Oracle RAC日記
- IPython Interactive Computing and Visualization Cookbook(Second Edition)
- 二進(jìn)制分析實(shí)戰(zhàn)
- 從實(shí)踐中學(xué)習(xí)sqlmap數(shù)據(jù)庫(kù)注入測(cè)試
- 數(shù)據(jù)庫(kù)應(yīng)用系統(tǒng)技術(shù)
- Oracle 11g數(shù)據(jù)庫(kù)管理員指南
- MySQL性能調(diào)優(yōu)與架構(gòu)設(shè)計(jì)
- 數(shù)據(jù)分析方法及應(yīng)用:基于SPSS和EXCEL環(huán)境