gpt4 book ai didi

java - 在 Java 中复制对象

转载 作者:IT老高 更新时间:2023-10-28 20:48:33 24 4
gpt4 key购买 nike

我有一个需要在 Java 中复制的对象。我需要在不更改原始对象本身的情况下创建一个副本并对其运行一些测试。

我假设我需要使用 clone() 方法,但这是 protected 。在网上做了一些研究后,我可以看到这可以用我类(class)中的公共(public)方法覆盖。但我找不到如何做到这一点的解释。这怎么可能?

另外,这是实现我需要的最佳方式吗?

最佳答案

使用复制构造函数的另一种选择(来自 Java Practices):

public final class Galaxy {

public Galaxy (double aMass, String aName) {
fMass = aMass;
fName = aName;
}

/**
* Copy constructor.
*/
public Galaxy(Galaxy aGalaxy) {
this(aGalaxy.getMass(), aGalaxy.getName());
//no defensive copies are created here, since
//there are no mutable object fields (String is immutable)
}

/**
* Alternative style for a copy constructor, using a static newInstance
* method.
*/
public static Galaxy newInstance(Galaxy aGalaxy) {
return new Galaxy(aGalaxy.getMass(), aGalaxy.getName());
}

public double getMass() {
return fMass;
}

/**
* This is the only method which changes the state of a Galaxy
* object. If this method were removed, then a copy constructor
* would not be provided either, since immutable objects do not
* need a copy constructor.
*/
public void setMass( double aMass ){
fMass = aMass;
}

public String getName() {
return fName;
}

// PRIVATE /////
private double fMass;
private final String fName;

/**
* Test harness.
*/
public static void main (String... aArguments){
Galaxy m101 = new Galaxy(15.0, "M101");

Galaxy m101CopyOne = new Galaxy(m101);
m101CopyOne.setMass(25.0);
System.out.println("M101 mass: " + m101.getMass());
System.out.println("M101Copy mass: " + m101CopyOne.getMass());

Galaxy m101CopyTwo = Galaxy.newInstance(m101);
m101CopyTwo.setMass(35.0);
System.out.println("M101 mass: " + m101.getMass());
System.out.println("M101CopyTwo mass: " + m101CopyTwo.getMass());
}
}

关于java - 在 Java 中复制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/475842/

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