- A setter's purpose is to allow an attribute (instance variable) to be changed from outside of the class.
- This is needed because your instance variables are declared private (make sure you do it), which means they can only be accessed from within the class.
- Once
you have declared your instance variables, the basic setters "write
themselves" in that in most cases, all the information you need to know
to write a setter can be derived from the declaration of the
corresponding instance variable.
- Here is the syntax for every basic setter:
public void setInstanceVariable(
DataTypeOfInstanceVariable
newValue)
{
instanceVariable = newValue;
}
- In certain cases, you may wish to write a setter that checks the incoming value, and only sets the instance variable if it is valid.
- This type of setter could fail to set the instance variable, so should have a return type of boolean (true/false) rather than void.