Java Reference
In-Depth Information
PITFALL: (continued)
You may encounter this problem even with classes defi ned after Java version 5.0. In
Java version 5.0 and later, it is perfectly legal to use Object as a return type for a
clone method (even if that is not the preferred return type). When in doubt, it causes
no harm to include the type cast. For example, the following is legal for the clone
method of the class Sale defi ned in the previous section:
Sale copySale = originalSale.clone();
However, adding the following type cast produces no problems:
Sale copySale = (Sale)originalSale.clone();
When in doubt about the clone method of a class, include the type cast.
PITFALL: Limitations of Copy Constructors
Copy constructors work well in most simple cases. However, there are situations where
they do not—indeed, cannot—do their job. That is why Java favors using the method
clone in place of using a copy constructor. Here is a simple example of where the copy
constructor does not do its job, but the clone method does.
For this discussion, assume that the classes Sale and DiscountSale each have
a clone method added. The defi nitions of these clone methods are given in the
previous subsection.
Suppose you have a method with the following heading (the methods Sale and
DiscountSale were defi ned in Displays 8.1 and 8.2 ):
/**
Supposedly returns a safe copy of a. That is, if b is the array
returned, then b[i] is supposedly an independent copy of a[i].
*/
public static Sale[] badCopy(Sale[] a)
{
Sale[] b = new Sale[a.length];
for ( int i = 0; i < a.length; i++)
b[i] = new Sale(a[i]); //Problem here!
return b;
}
Now if your array a contains objects from derived classes of Sale , such as objects of
type DiscountSale , then badCopy(a) will not return a true copy of a . Every element
of the array badCopy(a) will be a plain old Sale , because the Sale copy constructor
produces only plain old Sale objects; no element in badCopy(a) will be an instance
of the class DiscountSale .
 
Search WWH ::




Custom Search