Java Reference
In-Depth Information
assuming that Name implements the interface Comparable . (See Question 9 of Appendix D.) Now if
we write
rob.setLast("Smith");
the list changes to
Rob Smith
Jesse Java
This sorted list is no longer alphabetical. One solution to this problem is to require the client to use
immutable objects, as the next segment describes.
30.5
As Chapter 10 indicated, an immutable object is one whose data fields cannot be altered by a client.
The class to which an immutable object belongs has no public mutator (set) methods, so once you cre-
ate the object, you cannot change its data fields. If you need to change them, you will have to discard
the object and create a new one with the revised fields. Such a class is said to be read only . A client
that places immutable objects into a sorted list cannot alter those objects and thus cannot destroy the
sorted order of the list.
Note: An immutable object belongs to a read-only class. Such a class prevents a client
from changing the values of its data fields.
Note: When a collection—such as a sorted list—organizes objects in a certain way, a client
should not destroy this organization by altering the objects directly. Yet if the client retains
references to the objects, that is exactly what a client could do. You can prevent this problem
by adding only immutable objects to the collection.
30.6
Mutable or immutable? Most classes have set methods, so their instances are mutable. Being able
to change an object's data is convenient and efficient, particularly when an object's state must change
often during the course of a program's execution. For example, a bank must regularly update the
object that represents your checking account. If that object were immutable, it would be discarded and
a new object representing the updated data would be created each time there was a change. But revis-
ing an object takes less time than replacing it.
On the other hand, sharing a mutable object can be dangerous. Suppose that you have two ref-
erences, a and b , to the same object. If you use a to modify the object, you might get confused when
you use b to reference it. But sharing immutable objects is safe, since no matter how you reference
them, they remain unchanged.
Programming Tip: Use an immutable object if it will be shared or added to a collection
that can be corrupted by changes to the object. Use a mutable object if its data will change
frequently.
Creating a Read-Only Class
30.7
To convert the previous class Name into a read-only class, we can change the access modifiers of the
methods setFirst , setLast , and setName from public to private to prevent a client from invoking
them. (We could instead omit these methods altogether, modifying the other methods that invoke
them.) We also omit Name 's method giveLastNameTo .
 
Search WWH ::




Custom Search