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

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
主站蜘蛛池模板: 原平市| 惠东县| 商洛市| 邻水| 佛山市| 信丰县| 崇州市| 阳高县| 永定县| 新化县| 建宁县| 江永县| 贵溪市| 溧阳市| 长岭县| 吉木乃县| 曲松县| 巴林右旗| 海兴县| 剑川县| 余干县| 迭部县| 东丽区| 瓦房店市| 阿合奇县| 灵寿县| 嘉祥县| 独山县| 剑川县| 汪清县| 邳州市| 郓城县| 庆阳市| 常德市| 永兴县| 县级市| 岳阳县| 秀山| 台南县| 博爱县| 民县|