zuai-logo

Mutator Methods

Emily Wilson

Emily Wilson

5 min read

Listen to this study note

Study Guide Overview

This study guide covers mutator (setter) methods in Java. It explains their purpose (changing instance variable values), structure (typically void with parameters), and contrasts them with accessor methods. The guide demonstrates creating mutator methods within the Student class example, while highlighting the concept of immutable classes (like the Assignment class) which lack mutators. Finally, it shows how to use mutator methods to modify object states.

Introduction to Mutator Methods

Now that we are done with accessor methods, we will move on to mutator methods (also called setter methods). Mutator methods change the values of instance variables of an object by setting them to another value as a parameter. The headers for these methods are basically the opposite of accessor methods.

While accessor methods have a return type and no parameters, mutator methods usually have no return type (they are usually void methods) and have a parameter (the value which to change the object to). Like accessor methods, sometimes we don't want other clients to change the data of an object, thus there will not be a mutator method for that instance variable.

If a class has no mutator methods, then that class is said to be immutable. In our example, we will have the Assignment class be immutable with no mutator methods.

Writing Mutator Methods for the Student Class

Now, we will write mutator methods for the Student classes for the varia...