- 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.
推薦閱讀
- 數據庫應用實戰
- 大數據可視化
- 數據庫開發實踐案例
- INSTANT Cytoscape Complex Network Analysis How-to
- 大數據Hadoop 3.X分布式處理實戰
- 深入淺出 Hyperscan:高性能正則表達式算法原理與設計
- 金融商業算法建模:基于Python和SAS
- 數據庫設計與應用(SQL Server 2014)(第二版)
- gnuplot Cookbook
- 爬蟲實戰:從數據到產品
- 聯動Oracle:設計思想、架構實現與AWR報告
- Mastering ROS for Robotics Programming(Second Edition)
- MySQL技術內幕:InnoDB存儲引擎
- Rust High Performance
- 區塊鏈應用開發指南:業務場景剖析與實戰