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

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
主站蜘蛛池模板: 页游| 卓尼县| 宾川县| 永新县| 新建县| 侯马市| 边坝县| 皮山县| 渝北区| 安远县| 隆尧县| 高清| 德化县| 建德市| 内江市| 肥西县| 环江| 岳阳县| 平乡县| 黎城县| 石泉县| 莒南县| 镇宁| 鸡东县| 阳泉市| 文水县| 杭州市| 义马市| 南华县| 景谷| 阿克苏市| 曲阳县| 麻阳| 柳林县| 嫩江县| 灌云县| 西峡县| 招远市| 乐安县| 南江县| 罗江县|