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

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
主站蜘蛛池模板: 渝中区| 临西县| 磐安县| 汽车| 金阳县| 平遥县| 丰县| 正宁县| 景东| 南靖县| 安化县| 东港市| 屏东市| 清丰县| 大埔县| 美姑县| 日喀则市| 阜康市| 昌图县| 泰州市| 沛县| 达尔| 平果县| 商城县| 东乌珠穆沁旗| 松溪县| 寿阳县| 南京市| 五家渠市| 民勤县| 来凤县| 农安县| 镇远县| 石首市| 榆社县| 崇州市| 竹北市| 大埔县| 宜兰县| 呼和浩特市| 临泽县|