Methods: How to Write Them
| English | Chinese | Pinyin |
|---|---|---|
| accessor | 访问方法 | fǎng wèn fāng fǎ |
| mutator | 修改方法 | xiū gǎi fāng fǎ |
Writing a method
- A method has a header and a body.
- Header:
public int addScore(int s)— access, return type, name, parameters. - Body: the statements in
{ }that do the work. - The method can read and change the object's instance variables.
Return values
- A method's return type says what it hands back; use
return value;to send it. public int getScore() { return score; }returns the current score.- A
voidmethod returns nothing — it just does its job (e.g. printing). - The returned type must match the header's return type.
Accessors and mutators
- An accessor (getter) 访问方法 returns information without changing the object:
getScore(). - A mutator (setter) 修改方法 changes the object's state:
addScore(s)orsetName(n). - Getters are usually
int/String-returning; setters are usuallyvoid. - Together they form the object's public interface over its private data.
Methods can validate
- Because outside code goes through methods, a method can check before it acts.
public void setScore(int s) { if (s >= 0) score = s; }rejects a negative score.- This is the payoff of encapsulation — the data can't be set to a bad value directly.
- Well-written methods keep the object's state valid.
A non-void method must return a value of the declared type on every path. If getScore() says it returns int, every branch must return an int — a missing return is a compile error. A void method returns nothing, so return; (or no return) is correct there; writing return value; in a void method won't compile.
An accessor and a mutator:
- Accessor:
public int getScore() { return score; }— reads, returnsint. - Mutator:
public void addScore(int s) { score += s; }— changes state, returns nothing. student.addScore(10); int now = student.getScore();
A method has a header (access, return type, name, parameters) and a body. A non-void method must return a value of its declared type; a void method returns nothing. Accessors (getters) return state without changing it; mutators (setters) change state and can validate the new value.
An accessor returns a value
addScore changes state (void); getScore returns the value.
A method that returns information without changing the object is a(n)...
Accessors read and return; mutators change state.
A void method...
void = no return value; it just performs an action.
A non-void method must return a value of its declared type on every path.
A missing return on some branch is a compile error.
Which method can validate its input before changing state?
A setter can check (e.g. reject negatives) before assigning.
Writing return value; inside a void method compiles fine.
A void method can't return a value — that won't compile.