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.
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.
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:
-
Incorrect
Correct
No Answer was selected
Invalid Answer
Which of the following is NOT a characteristic of a mutator?
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: