Java Reference
In-Depth Information
PITFALL: (continued)
If we instead use the method
clone
, things work out as they should; the following is
the correct way to defi ne our copy method:
public static
Sale[] goodCopy(Sale[] a)
{
Sale[] b =
new
Sale[a.length];
for
(
int
i = 0; i < a.length; i++)
b[i] = a[i].clone();
return
b;
}
Because of late binding (polymorphism),
a[i].clone()
always means the correct
version of the
clone
method. If
a[i]
is an object created with a constructor of the
class
DiscountSale
,
a[i].clone()
will invoke the defi nition of
clone()
given in the
defi nition of the class
DiscountSale
. If
a[i]
is an object created with a constructor
of the class
Sale
,
a[i].clone()
will invoke the defi nition of
clone()
given in the
defi nition of the class
Sale
. This is illustrated in Display 8.5 .
This may seem like a sleight of hand. After all, in the classes
Sale
and
DiscountSale
,
we defi ned the method
clone
in terms of copy constructors. We reproduce the defi ni-
tions of
clone
from the class
Sale
and
DiscountSale
as follows:
//For Sale class
public
Sale clone()
{
return new
Sale(
this
);
}
//For DiscountSale class
public
DiscountSale clone()
{
return new
DiscountSale(
this
);
}
So, why is using the method
clone
any different than using a copy constructor? The
difference is simply that the method creating the copy of an element
a[i]
has the
same name
clone
in all the classes, and polymorphism works with method names.
The copy constructors named
Sale
and
DiscountSale
have different names, and
polymorphism has nothing to do with methods of different names.
We will have more to say about the clone method in Chapter 13 when we discuss
the
Cloneable
interface.
■