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

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
主站蜘蛛池模板: 永年县| 鹿邑县| 新邵县| 中牟县| 龙门县| 龙游县| 东乡族自治县| 柳江县| 体育| 三明市| 华宁县| 邢台市| 平乡县| 茌平县| 武冈市| 陕西省| 朝阳县| 龙南县| 彭泽县| 宾阳县| 汕尾市| 监利县| 碌曲县| 东乡族自治县| 绥芬河市| 浠水县| 大埔县| 闽清县| 鄂尔多斯市| 桃园县| 镇沅| 寿光市| 全南县| 大名县| 水富县| 名山县| 台北市| 宜君县| 长泰县| 石家庄市| 临澧县|