Java Reference
In-Depth Information
FIGURE 30-5
An instance of Name and its shallow clone
first
last
april , an instance of Name
"April"
"Jones"
twin , the shallow clone april.clone()
last
first
A shallow clone is good enough for the class Name . Recall that instances of String are immutable.
Having an instance of Name and its clone share the same strings is not a problem because no one can
change the strings. This is good news since, like many classes that Java provides, String has no method
clone . Thus, if we change the clone's last name by writing
twin.setLast("Smith");
twin 's last name will be Smith , but april 's will still be Jones , as Figure 30-6 shows. That is,
setLast changes twin 's data field last so that it references another string Smith . It does not
change april 's last , so it still references Jones .
FIGURE 30-6
The clone twin , after the statement twin.setLast(“Smith”)
changes one of its data fields
first
last
april , an instance of Name
"Jones"
"April"
"Smith"
twin , the shallow clone april.clone()
first
last
Programming Tip: Shallow copies of data fields that reference immutable objects are
typically sufficient for a clone. Sharing an immutable object is usually safe.
 
Search WWH ::




Custom Search