AP Computer Science A · Unit 3: Class Creation
3.5 Mutator Methods
What mutator methods do
A mutator method (setter) changes the value of an object's instance variable(s). It typically has a void return type, is often named `setVariableName`, and takes a parameter whose value is assigned to the instance variable using the `this` keyword to distinguish it from the parameter.
Using 'this' to avoid ambiguity
When a parameter has the same name as an instance variable, `this.variableName` refers to the instance variable while the plain name refers to the parameter. Writing `this.age = age;` correctly assigns the parameter's value to the object's field, avoiding shadowing confusion.
Validating data in mutators
Mutators can include logic to validate input before assigning it, protecting the object's state. For example, a setter for age might check that the parameter is non-negative before updating the instance variable, ignoring or adjusting invalid values instead of blindly overwriting them.
Key terms
- Mutator method
- A method (setter) that changes the value of an object's instance variable, typically void return type.
- Typical setter naming convention
- setVariableName, e.g., setAge, setBalance, setName.
- this keyword in a setter
- Refers to the current object's instance variable, distinguishing it from a same-named parameter.
- Why validate in a mutator?
- To ensure only valid data updates the instance variable, protecting the object's state.
- Example setter with this
- public void setAge(int age) { this.age = age; }
Try an AP-style question
What does a mutator (setter) method do?
- Creates a brand-new class
- Deletes the object from memory
- Changes an instance variable's value
- Only returns a stored value
Show the answer
C. Modifies state.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.5 free in APrep