Java Reference
In-Depth Information
30.9
We have one more concern. Imagine a class that has a
Name
object as a data field. The class has acces-
sor methods, including one that returns the
Name
field, but has no mutator methods. However, a client
of this class can access the
Name
field and then use
Name
's set methods to alter the field's value. In
other words, the class is not read only. To make it read only, we can define the field as final. Note that
the fields of
ImmutableName
are strings, which are immutable, so we need not make them final.
Note:
Design guidelines for a read-only class
•
The class should be final.
•
Data fields should be private.
•
The class should not have public set methods.
•
Data fields that are mutable objects should be final.
Question 1
Define a constructor for
ImmutableName
that has a
Name
object as a parameter.
30.10
Although immutable objects are desirable for certain applications, mutable objects have their place.
Sometimes we will want to represent an object in both immutable and mutable forms. In such cases, a
pair of
companion classes
can be convenient. The classes
ImmutableName
and
Name
are examples of
two such companion classes. The objects in both classes represent names, but one type of object can-
not be altered, while the other can be.
To make the classes even more convenient, you could include constructors and/or methods that
convert an object from one type to the other. For example, we might add the following constructor
and method to the class
ImmutableName
:
// add to the class ImmutableName:
public
ImmutableName(Name aName)
{
first = aName.getFirst();
last = aName.getLast();
}
// end constructor
public
Name getMutable()
{
return new
Name(first, last);
}
// end getMutable
Similarly, we could add the following constructor and method to the class
Name
:
// add to the class Name
public
Name(ImmutableName aName)
{
first = aName.getFirst();
last = aName.getLast();
}
// end constructor
public
ImmutableName getImmutable()
{
return new
ImmutableName(first, last);
}
// end getMutable
Figure 30-3 illustrates the two classes
Name
and
ImmutableName
.