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

Accessors and mutators

Accessor methods are those that allow an object's data to be accessed. These methods can get the data, but not change it. This is a great way to protect the data from being changed. Accessor methods are also referred to as Getters methods. 

Mutator methods, also known as setter methods, allow the object's instance variables to be changed. 

Here is a complete set of accessors and mutators for our Bicycle class:

// Accessors (Getters)
public int getGears() {
return this.gears;
}

public double getCost() {
return this.cost;
}

public double getWeight() {
return this.weight;
}

public String getColor() {
return this.color;
}

// Mutators (Setters)
public void setGears(int nbr) {
this.gears = nbr;
}

public void setCost(double amt) {
this.cost = amt;
}

public void setWeight(double lbs) {
this.weight = lbs;
}

public void setColor(String theColor) {
this.color = theColor;
}

As you can see in the preceding code, we use the this reference for the current object. The accessors do not take any parameters and simply return the value of the instance variable. The mutators take a parameter and use its value in assigning a new value to an instance variable. 

主站蜘蛛池模板: 苏州市| 沾化县| 广东省| 七台河市| 襄汾县| 广州市| 哈密市| 南安市| 丰都县| 繁峙县| 陇南市| 祁门县| 达州市| 平定县| 余干县| 鹤山市| 江川县| 博湖县| 稻城县| 隆昌县| 渭南市| 满城县| 葫芦岛市| 洪湖市| 桦甸市| 稷山县| 中山市| 通江县| 舞钢市| 仁布县| 五指山市| 新龙县| 凤山县| 乌兰浩特市| 花垣县| 喜德县| 改则县| 兴隆县| 宜川县| 忻州市| 祥云县|