Mutator Methods

Corresponding to each get method, programmers also provide a public set method to change the value of a private instance variable in a class. These are called mutator methods (or settters or set or modifier methods). They are void methods meaning that they do not return a value, but they do take a parameter, the new value for the instance variable. Here are some examples of how to write a set method for an instance variable:

class ExampleTemplate {

    //Instance variable declaration
    private typeOfVar varName;

    // Mutator (setter) method template
    public void setVarName(typeOfVar newValue) {
       varName = newValue;
    }
}

Here’s an example of the Student class with a mutator method called setName():

class Student {

   //Instance variable name
   private String name;

   /** setName sets name to newName
    *  @param newName                */
   public void setName(String newName) {
      name = newName;
   }

   public static void main(String[] args) {
      // To call a set method, use objectName.setVar(newValue)
      Student s = new Student();
      s.setName("Ayanna");
   }
  }

Notice the difference between set (mutator) and get (accessor) methods in the following figure. Getters return an instance variable’s value and have the same return type as this variable and no parameters. Setters have a void return type and take a new value as a parameter to change the value of the instance variable.

../_images/get-set-comparison.png

Figure 1: Comparison of set and get methods

exercise Check your understanding

Mutator methods do not have to have a name with “set” in it, although most do. They can be any methods that change the value of an instance variable or a static variable in the class.

groupwork Programming Challenge : Class Pet Setters

Animal Clinic
  1. Continue working with your pet class from the last lesson.

  2. Add set methods for each of the 5 instance variables. Make sure you use good commenting!

  3. Test each of the set methods in the main method.

Practice

Summary

  • A void method does not return a value. Its header contains the keyword void before the method name.

  • A mutator method is often a void method that changes the values of instance variables or static variables.

You have attempted of activities on this page