Java Reference
In-Depth Information
Display 8.5
Copy Constructor Versus clone Method (part 1 of 2)
1 /**
2 Demonstrates where the clone method works,
3 but copy constructors do not.
4*/
5 public class CopyingDemo
6 {
This program assumes that a clone
method has been added to the class
Sale and to the class DiscountSale .
7 public static void main(String[] args)
8 {
9 Sale[] a = new Sale[2];
10 a[0] = new Sale("atomic coffee mug", 130.00);
11 a[1] = new DiscountSale("invisible paint", 5.00, 10);
12
int i;
13 Sale[] b = badCopy(a);
14 System.out.println("With copy constructors:");
15 for (i = 0; i < a.length; i++)
16 {
17 System.out.println("a[" + i + "] = " + a[i]);
18 System.out.println("b[" + i + "] = " + b[i]);
19 System.out.println();
20 }
21 System.out.println();
22 b = goodCopy(a);
23 System.out.println("With clone method:");
24 for (i = 0; i < a.length; i++)
25 {
26 System.out.println("a[" + i + "] = " + a[i]);
27 System.out.println("b[" + i + "] = " + b[i]);
28 System.out.println();
29 }
30 }
31 /**
32 Supposedly returns a safe copy of a. That is, if b is the
33 array returned, then b[i] is supposedly an independent copy of a[i].
34 */
35 public static Sale[] badCopy(Sale[] a)
36 {
37 Sale[] b = new Sale[a.length];
38 for ( int i = 0; i < a.length; i++)
39 b[i] = new Sale(a[i]);// Problem here!
40
return b;
41 }
42
Search WWH ::




Custom Search