上QQ阅读APP看书,第一时间看更新
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