- Hands-On Design Patterns with Java
- Dr. Edward Lavieri
- 158字
- 2021-06-24 14:57:59
Constructors
Constructors are a special kind of method that are run when an object is initialized. We use constructors to set up an object with default values. Let's take a look at what our Bicycle class constructor would be. The following code should be placed in the Bicycle class after the instance variable section:
// constructor
Bicycle() {
this.color = "Navy Blue";
}
As you can see from the preceding, the constructor sets the color of the newly instantiated object to Navy Blue. When we run the following Driver class, an instance of Bicycle is instantiated, causing the Bicycle class constructor to run, and then a call to the outputData() method is made:
public class Driver {
public static void main(String[] args) {
Bicycle myBike = new Bicycle();
myBike.outputData();
}
}
The preceding code shows the Driver class. The following is the output from the outputData() method call.

outputData() execution results
推薦閱讀
- InfluxDB原理與實戰(zhàn)
- 新型數(shù)據(jù)庫系統(tǒng):原理、架構(gòu)與實踐
- Oracle RAC 11g實戰(zhàn)指南
- 大數(shù)據(jù):規(guī)劃、實施、運維
- Microsoft Power BI數(shù)據(jù)可視化與數(shù)據(jù)分析
- 智能數(shù)據(jù)時代:企業(yè)大數(shù)據(jù)戰(zhàn)略與實戰(zhàn)
- Oracle PL/SQL實例精解(原書第5版)
- 編寫有效用例
- 淘寶、天貓電商數(shù)據(jù)分析與挖掘?qū)崙?zhàn)(第2版)
- Augmented Reality using Appcelerator Titanium Starter
- Kubernetes快速進(jìn)階與實戰(zhàn)
- 碼上行動:利用Python與ChatGPT高效搞定Excel數(shù)據(jù)分析
- MySQL性能調(diào)優(yōu)與架構(gòu)設(shè)計
- 代碼的未來
- 從零進(jìn)階!數(shù)據(jù)分析的統(tǒng)計基礎(chǔ)(第2版)