Java Reference
In-Depth Information
Had we failed to clone the data field fullName —that is, had we omitted the statement
theCopy.fullName = (Name)fullName.clone();
the student's full name would be shared by the original instance and its clone. Figure 30-8
illustrates this situation.
FIGURE 30-8
An instance of Student and its clone, including a shallow copy
of fullName
first
last
fullName
fullName
"Lo"
"Kim"
"1234"
id
id
An instance of Student
The shallow clone
Question 4 Suppose that x is an instance of Student and y is its clone; that is,
Student y = (Student)x.clone();
a.
If you change x 's last name by executing
Name xName = x.getName();
xName.setLast("Smith");
does y 's last name change? Explain.
b.
If you fail to clone fullName within Student 's clone method, will changing x 's last name
change y 's last name as well? Explain.
Note: Within each public clone method, you typically perform the following tasks:
Invoke the clone method of the superclass by writing super.clone() .
Enclose this call to clone in a try block, and write a catch block to handle the possible
exception CloneNotSupportedException . You can skip this step if super.clone() invokes
a public clone method.
Clone the mutable data fields of the object that super.clone() returned, when possible.
Return the clone.
30.19
Example: Cloning a CollegeStudent object. Now let's add a clone method to a subclass of
Student . Segment C.8 of Appendix C defines such a subclass, namely the class CollegeStudent .
After we add an implements clause to its definition, the class has the following form:
public class CollegeStudent extends Student implements Cloneable
{
private int year; // year of graduation
private String degree; // degree sought
Search WWH ::




Custom Search