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

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. 

主站蜘蛛池模板: 汤阴县| 浦城县| 黄梅县| 诸暨市| 深州市| 西昌市| 墨脱县| 临高县| 利辛县| 顺义区| 太白县| 行唐县| 台前县| 德格县| 水富县| 景谷| 孙吴县| 丰镇市| 澎湖县| 绥化市| 神池县| 巴林右旗| 原阳县| 丰城市| 布尔津县| 望都县| 嘉峪关市| 平利县| 当阳市| 盘锦市| 师宗县| 高邮市| 专栏| 喀喇沁旗| 永修县| 龙泉市| 鄂尔多斯市| 海盐县| 漠河县| 安新县| 沈丘县|