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

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
主站蜘蛛池模板: 北辰区| 大洼县| 大丰市| 白山市| 抚远县| 金川县| 尚志市| 文山县| 灵宝市| 台前县| 韶关市| 崇州市| 望谟县| 清涧县| 壶关县| 星子县| 延庆县| 平乐县| 梓潼县| 正宁县| 萨迦县| 宁国市| 芷江| 根河市| 仁寿县| 武陟县| 开封县| 南澳县| 昆山市| 闻喜县| 黄浦区| 河池市| 尼玛县| 葫芦岛市| 江北区| 五莲县| 旌德县| 易门县| 广西| 水城县| 青神县|