Java Reference
In-Depth Information
house1: House
Memory
id = 1
area = 1750.50
whenBuilt
1
1750.50
reference
whenBuilt: Date
date object contents
house2 = house1.clone()
house2: House
Memory
id = 1
area = 1750.50
whenBuilt
1
1750.50
reference
F
IGURE
15.6
The default
clone
method performs a shallow copy.
deep copy
To perform a deep copy for a
House
object, replace the
clone()
method in lines 26-27
with the following code:
public
Object clone()
throws
CloneNotSupportedException {
// Perform a shallow copy
House houseClone = (House)
super
.clone();
// Deep copy on whenBuilt
houseClone.whenBuilt = (java.util.Date)(whenBuilt.clone());
return
houseClone;
}
or
public
Object clone() {
try
{
// Perform a shallow copy
House houseClone = (House)
super
.clone();
// Deep copy on whenBuilt
houseClone.whenBuilt = (java.util.Date)(whenBuilt.clone());
return
houseClone;
}
catch
(CloneNotSupportedException ex) {
return null
;
}
}
Now if you clone a
House
object in the following code:
House house1 =
new
House(
1
,
1750.50
);
House house2 = (House)house1.clone();
house1.whenBuilt
==
house2.whenBuilt
will be
false
.
house1
and
house2
refer-
ence two different
Date
objects.
15.22
Can you invoke the
clone()
method to clone an object if the class for the object
does not implement the
java.lang.Cloneable
? Does the
Date
class imple-
ment
Cloneable
?
✓
✓
Check
Point
15.23
What would happen if the
House
class (defined in Listing 15.9) did not override the
clone()
method or if
House
did not implement
java.lang.Cloneable
?