Accessors/getters - public methods that are used to inspect the value of instance variables
For clients to be able to use a class, implementers of an ADT will often need to provide one or more public functions that allow the user to "see" (inspect) the current values of the private instance variables of an object. These "read-only" type of methods are called accessor functions.
E.g.,
Two appropriate accessor functions of a class TwoDice are getDice1() and getDice2() which can be used to find the current value of one of the dice. The definition for getDice1() is:
public int getDice1()
{
return dice1 ;
}
with a similar definition for getDice2(). We can use these functions to store the value of the first die in the integer variable valueOfDie1 as shown below:
TwoDice roll = new TwoDice() ;
int valueOfDie1 = roll.getDice1() ;
In the method call roll.getDice1(), the object roll is the current object (the object for which the method is called) so that applying getDice1() to this object will return the value roll.dice1.
Mutators /Setters - Public methods that are used to alter the value of an instance variable.
Mutators should include data validation to ensure the values of instance variables do not exceed their permitted range.
E.g,
The TwoDice class has the interesting property that once a TwoDice object has been created, its value cannot be changed - no public methods have been provided to allow client code to do so. Such objects are said to be immutable which means they cannot be modified once they have been created. A number of Java's own classes has this property of providing only immutable objects - two such examples being the String and Color classes.
Class designers often provide what are called mutator or setter methods to enable client code to modify the value of an object. This is potentially dangerous as it may be seen to compromise the security of private data. It is therefore imperative that the implementer of an ADT provide appropriate data validation to ensure that the value of an attribute (instance variable) is set properly within the bounds of its allowable values. Appropriate mutator methods for our TwoDice class are setDice1( int n ) and setDice2( int n ), and the definition of the first of these is given below:
public void setDice1( int n )
{
assert (n >= 1) && (n <= 6) : "value of dice1 out of range: " + n ;
dice1 = n ;
}
Of interest here, is the use of an assertion which, if it evaluates to false, results in program execution being terminated.