Reputation: 329
I recently started a course on Java programming language. Going through the lectures, I found these two slides that are confusing me:
1.
If the class has a copy constructor, clone() can use the copy constructor to create and return a copy of the object.
public Sale(Sale obj) {
this.itemName = new String(obj.itemName);
this.itemPrice = obj.itemPrice;
}
public Sale clone() {
return new Sale(this);
}
2.
Even though the copy constructor and clone() do the same thing (when implemented like shown previously), in certain situations only clone() can work
This is the example shown (Sale and DiscountSale are implemented elsewhere):
public class CopyTest {
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]);
return b;
}
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;
}
public static void main(String[] args) {
Sale[] a = new Sale[2];
a[0] = new Sale("atomic coffee mug", 130.00);
a[1] = new DiscountSale("invisible paint", 5.00, 10);
int i;
Sale[] b = badCopy(a);
System.out.println("With copy constructors: ");
for (i = 0; i < a.length; i++) {
System.out.println("a[" + i + "] = " + a[i]);
System.out.println("b[" + i + "] = " + b[i]);
}
b = goodCopy(a);
System.out.println("With clone(): ");
for (i = 0; i < a.length; i++) {
System.out.println("a[" + i + "] = " + a[i]);
System.out.println("b[" + i + "] = " + b[i]);
}
}
}
What is the difference between the copy constructor and clone(), when clone() uses the copy constructor in its implementation? Why would only one work properly?
Upvotes: 4
Views: 1540
Reputation: 38910
It is better to go with copy constructors as long as the composed objects does not have any inheritance hierarchy.
Clone does not call constructor. Prefer clone when you have complex hierarchy of object composition. If not, stick to copy constructor.
Upvotes: 2