![]() |
![]() |
![]() |
![]() |
![]() |
|
Analogously, you do not need to assign an instance-variable value directly. Instead, you can assign an instance-variable value indirectly by defining an instance method that does the actual value assigning.
In general a setter is a method that inserts information into an instance. Setters are also known as mutators.
In the following Attraction class definition, for example, a setter
named setMinutes assigns a value to the minutes instance
variable:
public class Attraction {
public int minutes;
public Attraction () {minutes = 75;}
public Attraction (int m) {minutes = m;}
// Define getter:
public int getMinutes () {
return minutes;
}
// Define setter:
public void setMinutes (int m) {
minutes = m;
}
}
With setMinutes defined, you have
another way to assign a value to the minutes instance variable of a
particular attraction, x:
x.setMinutes(4)