Java Reference
In-Depth Information
FIGURE 30-3
The classes Name and ImmutableName
Name
ImmutableName
first
last
first
last
getFirst()
getLast()
getName()
setFirst(firstName)
setLast(lastName)
setName(firstName, lastName)
giveLastNameTo(aName)
toString()
getImmutable()
getFirst()
getLast()
getName()
toString()
getMutable()
30.11
Example. Let's see how we can use the previous additions to our companion classes. If we have a
Name object such as flexibleName in the statement
Name flexibleName = new Name("Maria", "Mocha");
and we no longer need the capability to change it, we can use ImmutableName 's constructor, as
follows:
ImmutableName fixedName = new ImmutableName(flexibleName);
The new object fixedName has the same data fields as flexibleName , but it is immutable. Alterna-
tively, we could have invoked Name 's method getImmutable , as follows:
ImmutableName fixedName = flexibleName.getImmutable();
Similarly, if we have another instance of ImmutableName , such as
ImmutableName persistent = new ImmutableName("Jesse", "Java");
and we find that we need to alter it, we can define a new mutable object as either
Name transient = new Name(persistent);
or
Name transient = persistent.getMutable();
The new object transient has the same data fields as persistent , but it also has set methods to
change them.
Question 2 Write Java statements that take the following steps:
Create an object of the class Name .
Convert the object to an immutable object without changing its data fields.
Add the immutable object to the sorted list nameList .
Question 3 Write Java statements that take the following steps:
Create an object of the class Immutable Name .
Convert the object to a mutable object without changing its data fields.
Change the last name of the new object.
Convert the revised mutable object to an immutable object.
Search WWH ::




Custom Search