AP® Computer Science A · Unit 3 · Topic 3.5
Accessors, Mutators, and the return Path
An accessor returns a copy of a private field's value, and a mutator changes it, usually after checking the new value makes sense — and a mutator can return something too, since what makes it a mutator is changing state, not its return type.
A field marked private is sealed off from code outside the class. Nothing out there can touch it directly, even to just look at it. So the class writes an accessor, a method like getScore, that hands back a copy of the value. The outside code never touches the real field — it just receives a number. A mutator, like setScore, works the other way: it takes an incoming value and writes it into the field, but first it can check that value. This is the entire point of keeping fields private: the class controls every read and every write, instead of trusting outside code to behave.
Mechanically, an accessor has a return type matching the field and simply returns it: public int getScore() { return score; }. A mutator takes a parameter and assigns it to the field, often after validation: public void setScore(int s) { if (s > 100) score = 100; else if (s < 0) score = 0; else score = s; }. Call setScore(150) and the clamp catches it — 150 is greater than 100, so score is set to 100, not 150. The field never sees the out-of-range value at all.
A common assumption is that mutators must be void because their job is to change state, not hand anything back. But a method's return type is a separate decision from what it does. A mutator can return a boolean reporting success, or the new value, and still be a mutator — what defines it is that it modifies the object. This separation between what a method does and what it returns matters again once objects start passing references to other objects, where a mutator might hand back the very object it just changed.
Key terms
- accessor
- A method that returns the value of a private field without allowing outside code to modify it directly.
- mutator
- A method that changes a private field's value, often after validating the new value.
- clamp
- Logic that forces an out-of-range value to the nearest valid boundary instead of rejecting it outright.
- private
- An access modifier that restricts a field or method to only be used inside its own class.
Watch it explained
- How it worksHow does an accessor copy a value out while a mutator writes a new value in?
- Worked exampleBuild getScore and setScore for a private score field that must stay between 0 and 100.
- Worked exampleTrace the call setScore(150) through a mutator that clamps out-of-range values.
- Common mistakeWhy isn't a mutator required to be a void method?
Check yourself
End of topic.