5.5. 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. 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:

// Setter template
public void setVariable(typeOfVar newVar)
   Variable = newVar;

// SetName() example
public void setName(String newName)
   name = newName;

// To call a setName method, use:

coding exercise Coding Exercise

Try the Student class below which this time has set methods added. You will need to fix the errors. The main method is in a separate Tester class and does not have access to the private instance variables in the other Student class. Change the main method so that it uses a public mutator method (set method) to access the value instead.

exercise Check your understanding

    5-5-1: Drag the definition from the left and drop it on the correct word on the right. Click the "Check Me" button to see if you are correct. Review the vocabulary.
  • gets and returns the value of an instance variable
  • accessor method
  • sets the instance variable to a value in its parameter
  • mutator method
  • initializes the instance variables to values
  • constructor
  • accessible from outside the class
  • public
  • accessible only inside the class
  • private

5.5.1. groupwork Programming Challenge : Class Pet Setters

Animal Clinic
  1. Copy your Awesome Animal Clinic Pet class from the last lesson into this Active Code window.

  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.

5.5.2. 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
Next Section - 5.6. Writing Methods