- Hands-On Design Patterns with Java
- Dr. Edward Lavieri
- 199字
- 2021-06-24 14:57:59
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.
推薦閱讀
- Hands-On Data Structures and Algorithms with Rust
- 分布式數據庫系統:大數據時代新型數據庫技術(第3版)
- MySQL基礎教程
- R數據科學實戰:工具詳解與案例分析(鮮讀版)
- 算法與數據中臺:基于Google、Facebook與微博實踐
- Flutter Projects
- 數據庫原理與應用
- HikariCP連接池實戰
- Oracle數據庫管理、開發與實踐
- Internet of Things with Python
- Deep Learning with R for Beginners
- Hands-On Deep Learning for Games
- Swift Functional Programming(Second Edition)
- Visual Studio 2012 and .NET 4.5 Expert Development Cookbook
- 碼上行動:利用Python與ChatGPT高效搞定Excel數據分析