1/3
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
As we saw in the last section, since we typically make instance variables private, we have to define getters if we want to allow code outside the class to access the value of particular instance variables.
By the same token, if we want to allow code outside the class to change the value of an instance variable we have to provide what is formally called a mutator method but which everyone actually calls a setter. A setter is a void method with a name that starts with set and that takes a single argument of the same type as the instance variable to be set. The effect of a setter, as you would probably expect, is to assign the provided value to the instance variable.
Just as you shouldn’t reflexively write a getter for every instance variable, you should think even harder about whether you want to write a setter. Not all instance variables are meant to be manipulated directly by code outside the class.
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.