gpt4 book ai didi

java - 使用 clone() 复制字段与复制构造函数 Java

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:17:38 25 4
gpt4 key购买 nike

我最近开始学习 Java 编程语言类(class)。通过讲座,我发现这两张幻灯片让我感到困惑:

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

这是显示的示例(Sale 和 DiscountSale 在其他地方实现):

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]);
}
}

}

当 clone() 在其实现中使用复制构造函数时,复制构造函数和 clone() 有什么区别?为什么只有一个可以正常工作?

最佳答案

只要组合对象没有任何继承层次结构,最好使用复制构造函数。

克隆不调用构造函数。当您具有复杂的对象组合层次结构时,更喜欢克隆。如果不是,请坚持复制构造函数。

关于java - 使用 clone() 复制字段与复制构造函数 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33055326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com