- 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.
推薦閱讀
- 數據庫基礎教程(SQL Server平臺)
- Unity 5.x Game AI Programming Cookbook
- 數據之巔:數據的本質與未來
- 從0到1:數據分析師養成寶典
- Learning Spring Boot
- Hadoop與大數據挖掘(第2版)
- 數據要素五論:信息、權屬、價值、安全、交易
- MySQL 8.x從入門到精通(視頻教學版)
- Apache Kylin權威指南
- 重復數據刪除技術:面向大數據管理的縮減技術
- Augmented Reality using Appcelerator Titanium Starter
- 智慧城市中的大數據分析技術
- 計算機視覺
- Spring MVC Beginner’s Guide
- 數據庫應用系統技術