Please enable JavaScript to use CodeHS

Chapter 5

Writing Classes

5.5 Mutator Methods

Just like you can control which instance variables an end user can access, developers can also control access to updating variables. This access is controlled by the mutator methods.

Mutator Methods

A mutator method is a method that is used to update the value of an instance (or static) variable. Since the method is designed to update a value, the method header often contains the void keyword since it doesn’t return a value.

Mutator methods set a new value. As such, they are often referred to as setter methods. Setter methods allow us to set the values of an object’s instance variables.

Creating Mutator Methods

As with accessor/getter methods you use a common convention when creating mutator methods. When creating mutator methods you should always use: set[Variable Name]. Some common examples include: setWidth(int width), setHeight(int height), setColor(Color color). Here are some examples of how to create these setter methods:

private int width = 10;
private int height = 3;
private Color rectCol = Color.blue;

public void setWidth(int newWidth)
{
  width = newWidth;
}

public void setHeight(int newHeight)
{
  height = newHeight;
}

public void setColor(Color color)
{
  rectCol = color;
}
Plain text

SuperHero Class with Mutator Methods

Student Setters

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    Which of the following is NOT a characteristic of a mutator?

Exercise: Rectangle class

Write your own accessor and mutator method for the Rectangle class instance variables.

You should create the following methods:

  • getLength
  • setLength
  • getWidth
  • setWidth
  • getArea
  • getPerimeter
  • toString- The output of a rectangle with width 10 and length 4 method should be:
Rectangle width: 10, Rectangle length: 4
Plain text