Java Reference
In-Depth Information
341
8.3 Accessors, Mutators, and Immutable Classes
Recall that a mutator method modifies the object on which it is invoked, whereas an
accessor method merely accesses information without making any modifications. For
example, in the BankAccount class, the deposit and withdraw methods are
mutator methods. Calling
account.deposit(1000);
modifies the state of the account object, but calling
double balance = account.getBalance();
does not modify the state of account .
You can call an accessor method as many times as you likeȌyou always get the same
answer, and it does not change the state of your object. That is clearly a desirable
property, because it makes the behavior of such a method very predictable. Some
classes have been designed to have only accessor methods and no mutator methods at
all. Such classes are called immutable. An example is the String class. Once a
string has been constructed, its contents never change. No method in the String
class can modify the contents of a string. For example, the toUpperCase method
does not change characters from the original string. Instead, it constructs a new string
that contains the uppercase characters:
String name = "John Q. Public";
String uppercased = name.toUpperCase(); // name is not
changed
An immutable class has no mutator methods.
An immutable class has a major advantage: It is safe to give out references to its
objects freely. If no method can change the object's value, then no code can modify
the object at an unexpected time. In contrast, if you give out a BankAccount
reference to any other method, you have to be aware that the state of your object may
changeȌthe other method can call the deposit and withdraw methods on the
reference that you gave it.
Search WWH ::




Custom Search