AP Computer Science A · Class creation
Accessor and mutator methods
1Accessor methods
An accessor (getter) returns information about an object without changing it:
public int getScore() {
return score;
}
- Non-void, usually no parameters.
- Named
getXby convention, orisXfor booleans:isFinished(). - Gives controlled, read-only access to private data.
An accessor can also return a calculated value: public double getAverage() { return (double) total / count; }.
Check yourself
An accessor method usually:
Show the answer
Returns a value without changing the object
Read-only.
2Mutator methods
A mutator (setter) changes an object's state:
public void setScore(int newScore) {
if (newScore >= 0) {
score = newScore;
}
}
- Usually
void, with a parameter for the new value. - Can validate input, rejecting invalid values, which is a key benefit of encapsulation.
Not every instance variable needs a setter: if a value should never change after construction (like an ID number), provide only a getter.
Accessors read private data, mutators change it safely, and direct access is blocked
Check yourself
Why might a setter check its parameter before changing a variable?
Show the answer
To keep the object's data valid
Validation.
3Methods that use other methods and objects
Methods can call other methods of the same class directly, and can access the private variables of another object of the same class:
public boolean beats(Player other) {
return score > other.score;
}
Methods can also return objects:
public Point midpoint(Point other) {
return new Point((x + other.x) / 2, (y + other.y) / 2);
}
Check yourself
Inside class Player, can a method read other.score where other is a Player and score is private?
Show the answer
Yes, private access is per class, not per object
Same class.
4Returning references safely
An accessor that returns a reference to a mutable private object (e.g. an ArrayList) lets outside code change it, breaking encapsulation. Return a copy, or return individual values instead.
Strings and primitives are safe to return.
Check yourself
Returning a direct reference to a private ArrayList allows:
Show the answer
Outside code to modify the list
Shared reference.
5Going deeper: writing them well, and protecting an object's state
Accessor (getter): returns information about an object without changing it.
- Non-void return type.
- Usually no parameters.
- Named
getSomething(orisSomethingfor a boolean).
Mutator (setter or modifier): changes the object's state.
- Often
void, with a parameter carrying the new value. - May return a boolean to report whether the change was made.
public class Thermostat {
private int target;
public int getTarget() {
return target;
}
public void setTarget(int degrees) {
if (degrees >= 50 && degrees <= 90) {
target = degrees;
}
}
public boolean isHeating(int roomTemp) {
return roomTemp < target;
}
}
Why not just make the variable public? A mutator can validate. setTarget(500) is ignored; a public variable could be set to anything. An accessor gives read access without write access.
Return, do not print. An accessor that prints is useless to code that needs the value.
public int getTarget() {
System.out.println(target); // wrong: nothing is returned
}
This does not even compile, since a non-void method must return a value.
The return type must match what is returned: returning a double from a method declared int is an error without a cast.
Accessors can compute. They need not simply hand back a stored variable:
public double getAverage() {
return (double) total / count;
}
Storing total and count and computing the average on request keeps the data consistent: there is no separate average to fall out of date.
Mutators that do more than set
deposit(amount)adds to a balance.addScore(s)updates both a total and a count.reset()restores the initial state.
Keep all related variables consistent in every mutator: if one changes, update the others that depend on it.
Worked example (trace):
public class Tally {
private int total;
private int count;
public void add(int value) {
total += value;
count++;
}
public double mean() {
return (double) total / count;
}
}
// elsewhere:
Tally t = new Tally();
t.add(8);
t.add(5);
t.add(2);
System.out.println(t.mean());
- No constructor is written: total and count start at 0.
- After three calls: total = 15, count = 3.
- Output:
5.0. - Calling
mean()before anyaddwould compute 0.0 / 0, giving NaN (not an exception, because the division is done in doubles).
Returning references: an accessor that returns a private array or ArrayList hands the caller a reference to the object's own data. The caller can then change it, bypassing every mutator.
public int[] getData() {
return data; // exposes the private array
}
Safer: return a copy.
public int[] getData() {
int[] copy = new int[data.length];
for (int i = 0; i < data.length; i++) {
copy[i] = data[i];
}
return copy;
}
Returning a String or a primitive is always safe: Strings are immutable and primitives are copied.
Methods calling methods: one method may use another of the same class without an object name: if (getTarget() > 80) { ... }. Reusing an existing method avoids repeating (and mis-writing) its logic.
void against non-void, at the call
int t = thermo.getTarget();uses the returned value.thermo.setTarget(70);stands alone as a statement.int x = thermo.setTarget(70);does not compile.
toString is an accessor: it returns a description and changes nothing.
Immutable classes: a class with no mutators, whose state is fixed by the constructor (like String), is the easiest to reason about.
Common mistakes
- Printing in place of returning.
- A mutator with a return type but no return statement, or an accessor declared void.
- A parameter with the same name as the instance variable, assigned without
this. - Changing state inside an accessor.
- Returning a private array directly.
- Updating one of two linked variables and not the other.
Check yourself
Which method header is appropriate for an accessor that reports a student's grade-point average?
Show the answer
public double getGpa()
An accessor returns a value and normally takes no parameters.
6For top marks
- Match the specification exactly: if a method is described as returning a value, it must not print it instead.
- Mutators in free-response questions often need conditions: check limits and update only when valid.
- Use accessors of other classes when you cannot access their private variables:
item.getPrice(), notitem.price. - Accessors should not change state; mutators should not normally return values unless specified (e.g. returning
trueif a change succeeded).
public boolean withdraw(int amt) { if (amt > 0 && amt <= balance) { balance -= amt; return true; } return false; }
Check yourself
From class Store, how should code get the price of an Item object it with private price?
Show the answer
it.getPrice()
Use the public accessor.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera