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

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. 

主站蜘蛛池模板: 赞皇县| 东乌| 长汀县| 宣汉县| 七台河市| 辽宁省| 临夏市| 资源县| 松溪县| 孟村| 进贤县| 化隆| 绥宁县| 明水县| 德钦县| 青岛市| 安多县| 东辽县| 武汉市| 新乐市| 卓资县| 东乡县| 年辖:市辖区| 广丰县| 盐源县| 民和| 太原市| 南城县| 富裕县| 常州市| 宜丰县| 哈尔滨市| 云梦县| 郑州市| 商南县| 甘肃省| 湘阴县| 南阳市| 诏安县| 沙湾县| 洛南县|