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

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. 

主站蜘蛛池模板: 繁峙县| 友谊县| 剑阁县| 庄浪县| 呼伦贝尔市| 石楼县| 宜良县| 宁强县| 木兰县| 眉山市| 扶余县| 永嘉县| 陇西县| 大丰市| 通海县| 库尔勒市| 什邡市| 桑日县| 英吉沙县| 四会市| 临漳县| 沙河市| 固安县| 锦州市| 黄山市| 鹿邑县| 河池市| 天柱县| 西林县| 宁乡县| 东乡县| 武汉市| 龙泉市| 阿鲁科尔沁旗| 杂多县| 裕民县| 楚雄市| 龙陵县| 建阳市| 通榆县| 锦屏县|