Java Reference
In-Depth Information
13
return
id;
14 }
15
16
public double
getArea() {
17
return
area;
18 }
19
20
public
java.util.Date getWhenBuilt() {
21
return
whenBuilt;
22 }
23
24 @Override
/** Override the protected clone method defined in
25
the Object class, and strengthen its accessibility */
public
Object clone()
26
throws
CloneNotSupportedException {
This exception is thrown if
House
does not implement
Cloneable
27
28 }
29
30 @Override
// Implement the compareTo method defined in Comparable
31
32
return super
.clone();
public int
compareTo(House o) {
if
(area > o.area)
33
return
1
;
34
else if
(area < o.area)
35
return
-1
;
36
else
37
return
0
;
38 }
39 }
The
House
class implements the
clone
method (lines 26-28) defined in the
Object
class. The header is:
protected native
Object clone()
throws
CloneNotSupportedException;
The keyword
native
indicates that this method is not written in Java but is implemented
in the JVM for the native platform. The keyword
protected
restricts the method to be
accessed in the same package or in a subclass. For this reason, the
House
class must override
the method and change the visibility modifier to
public
so that the method can be used in
any package. Since the
clone
method implemented for the native platform in the
Object
class performs the task of cloning objects, the
clone
method in the
House
class simply
invokes
super.clone()
. The
clone
method defined in the
Object
class may throw
CloneNotSupportedException
.
The
House
class implements the
compareTo
method (lines 31-38) defined in the
Comparable
interface. The method compares the areas of two houses.
You can now create an object of the
House
class and create an identical copy from it,
as follows:
CloneNotSupportedException
House house1 =
new
House(
1
,
1750.50
);
House house2 = (House)house1.clone();
house1
and
house2
are two different objects with identical contents. The
clone
method in
the
Object
class copies each field from the original object to the target object. If the field is
of a primitive type, its value is copied. For example, the value of
area
(
double
type) is
copied from
house1
to
house2
. If the field is of an object, the reference of the field is copied.
For example, the field
whenBuilt
is of the
Date
class, so its reference is copied into
house2
, as shown in Figure 15.6. Therefore,
house1.whenBuilt == house2.when-
Built
is true, although
house1 == house2
is false. This is referred to as a
shallow copy
rather than a
deep copy
, meaning that if the field is of an object type, the object's reference is
copied rather than its contents.
shallow copy
deep copy