7.6 Writing Mutator Methods

As we have discussed, we declare the instance variables as private to encapsulate the data of the class. We allow only the class methods to directly set the values of the instance variables. Thus, it is customary to provide a public mutator method for any instance variable that the client will be able to change. Because the method names usually start with “set,” mutator methods are often called setters.

The general form of a mutator method is the following:

public void setInstanceVariable( dataType newValue )
{
    // validate newValue, then assign to the instance variable
}

We declare mutator ...

Get Java Illuminated, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.