Accessors and Mutators
Accessors and Mutators: Reading and Updating Values
When you use an object, you often need to inspect a value or request a change to it. Accessors and mutators separate these two jobs. In Java, you can recognize their roles by reading what their method bodies do. Their names and return types provide clues, but their effects on the object's stored data decide the classification.
Reading a value
An accessor is a method that retrieves information about an object without changing its stored data. It may return a field directly or calculate a result from stored values. For example, a method that returns twice a stored ticket count can still be an accessor: calculating a result does not itself update the count.
Accessor names commonly begin with get, such as getTickets(). Methods that answer a true-or-false question often begin with is, such as isEmpty(). These are naming habits, so you should still inspect the implementation.
The returned value becomes available to the calling code. If that value is an integer, assigning it to a local variable gives the caller a separate integer value. Changing that local variable does not update the object's field.
Requesting a change
A mutator is a method whose role is to change an object's stored data. A setter is a common form: it receives a proposed replacement through a parameter.
Here is a ticket counter with an accessor and a validating setter:
public class TicketCounter {
private int tickets = 18;
public int getTickets() {
return tickets;
}
public boolean setTickets(int proposedTickets) {
if (proposedTickets < 0) {
return false;
}
tickets = proposedTickets;
return true;
}
}The setter accepts nonnegative counts and rejects negative ones. For this replacement setter, let v be the proposed value and s the stored count. Its governing rule is:
The Java type boolean represents true or false. Here, the setter returns whether it accepted the request. A mutator can return a value as well as update a field. Other mutators use void instead.
Following the effect of a call
Example: Suppose counter refers to a ticket counter with the initial count of 18. Calling counter.getTickets() returns 18 and leaves the count at 18. Calling counter.setTickets(25) returns true and replaces the count with 25. A later call to counter.setTickets(-3) returns false and leaves 25 stored.
Call or method role | Returned information | Effect on stored data |
|---|---|---|
Accessor | A value describing the object | Leaves stored data unchanged |
Accepted replacement setter | A result if the method provides one | Assigns the proposed value |
Rejected replacement setter | A rejection result if provided | Leaves the previous value unchanged |
Read assignments carefully. In tickets = proposedTickets;, the field receives the supplied value. Some setters instead use the same name for their field and parameter:
public void setTickets(int tickets) {
this.tickets = tickets;
}The keyword this makes this.tickets identify the object's field; plain tickets identifies the parameter here.
What to remember
- An accessor reads information without changing stored data.
- A mutator can update stored data, even if some calls leave it unchanged.
- Inspect assignments and validation, rather than relying only on names or return types.
- Changing a returned integer in a local variable does not change the object's field.
Example: Updating a Battery Charge Reading
A battery monitor uses an accessor to read its stored charge percentage and a mutator to request a replacement. Its Java implementation is shown below. Charge is stored as a whole-number percentage, and the setter accepts values from 0 through 100, including both endpoints.
public class BatteryMonitor {
private int charge = 64;
public int getCharge() {
return charge;
}
public boolean setCharge(int proposed) {
if (proposed < 0 || proposed > 100) {
return false;
}
charge = proposed;
return true;
}
}Assume monitor refers to a newly created monitor. Execute the parts in order on the same object.
a) A monitoring program reduces the reading by 19 percentage points using the following code. Find the stored charge afterward and the value of accepted.
int nextCharge = monitor.getCharge() - 19;
boolean accepted = monitor.setCharge(nextCharge);First, the accessor returns ________ percent without updating the field. Calculate the proposed replacement by subtracting 19 percentage points:
The local variable therefore contains 45, representing a charge of 45%. Calculating this variable has not yet changed the monitor.
Next, setCharge(nextCharge) receives 45. That value is within the accepted range, so execution reaches charge = proposed;. The field becomes 45, and the method returns true.
The final stored charge is 45%, and accepted is true.
b) Continuing from part a), the program first submits an invalid reading, then requests an increase of 12 percentage points. Find the final stored charge and the value of revised.
boolean rejectedRequest = monitor.setCharge(140);
boolean revised = monitor.setCharge(monitor.getCharge() + 12);The first setter call receives 140. Because 140 exceeds the maximum of 100, the method returns ________ before reaching its assignment. The variable name rejectedRequest does not change this returned value.
The stored charge remains ________ percent. Use the preserved reading when evaluating the next argument. The accessor in the second statement returns that reading without changing it.
Calculate the proposed increase:
The setter receives 57, which lies within the accepted range. It assigns 57 to the field and returns true, which is stored in revised.
The final stored charge is 57%, and revised is true. The invalid request did not replace the earlier valid reading.
A Lamp class stores its brightness in a private field and provides this mutator:
public void setBrightness(int level) {
if (level >= 0 && level <= 100) {
brightness = level;
}
}A client runs lamp.setBrightness(80); and later calls lamp.getBrightness(). Arrange the events in the order they happen.
1.
The condition compares level with the limits 0 and 100.
2.
The client evaluates the argument 80 and invokes setBrightness on the object that lamp refers to.
3.
The parameter level receives a copy of the value 80.
4.
The field brightness of that object is assigned the value 80.
5.
The method finishes and control returns to the client without any returned value.
6.
The later call lamp.getBrightness() returns 80 to the client.
A speaker object starts with volume equal to 4 and has the methods below. Execute the table's calls from top to bottom on that same object. Enter each returned value and the stored volume immediately after the call. Use exact integers or the words true and false.
public int getVolume() {
return volume;
}
public boolean setVolume(int proposed) {
if (proposed < 0 || proposed > 10) {
return false;
}
volume = proposed;
return true;
}| Call | Returned value | Stored volume after call |
| setVolume(8) | ||
| getVolume() | ||
| setVolume(-2) | ||
| setVolume(0) |