Java简单深度复制

Java简单深度复制,java,deep-copy,Java,Deep Copy,我在互联网上搜寻了一个更基本的解决方案,以解决不需要序列化或其他外部Java工具的对象深度复制问题。我的问题是,如何深度复制具有继承属性并且从其他对象聚合的对象?(不确定我说的是否正确……) 这与“浅拷贝和深拷贝之间有什么区别”的问题不同,因为这种类型的深拷贝有特定的参数,涉及继承和聚合(依赖其他对象作为其他对象的实例变量).我找到了一个既能使用继承又能使用聚合的解决方案-下面是一个简单的对象结构: //This is our SuperClass public class Human {

我在互联网上搜寻了一个更基本的解决方案,以解决不需要序列化或其他外部Java工具的对象深度复制问题。我的问题是,如何深度复制具有继承属性并且从其他对象聚合的对象?(不确定我说的是否正确……)


这与“浅拷贝和深拷贝之间有什么区别”的问题不同,因为这种类型的深拷贝有特定的参数,涉及继承和聚合(依赖其他对象作为其他对象的实例变量).

我找到了一个既能使用继承又能使用聚合的解决方案-下面是一个简单的对象结构:

//This is our SuperClass
public class Human {

    private String hairColor; //Instance variable

    public Human (String color) { // Constructor
        hairColor = color; 
    }

    public String getHairColor () { //Accessor method
        return hairColor;
    }
}

//This is our beard object that our 'Man' class will use
public class Beard {

    private String beardColor; // Instance variable

    public Beard (String color) { // Constructor
        beardColor = color;
    }

    public String getBeardColor () { // Accessor method
        return beardColor;
    }
}

// This is our Man class that inherits the Human class attributes
// This is where our deep copy occurs so pay attention here!
public class Man extends Human {

    // Our only instance variable here is an Object of type Beard
    private Beard beard;

    // Main constructor with arg
    public Man (Beard aBeard, String hairColor) {
        super(hairColor);
        beard = aBeard;
    }

    // Here is the COPY CONSTRUCTOR - This is what you use to deep copy
    public Man (Man man) {
        this(new Beard(man.getBeard().getBeardColor()), man.getHairColor());
    }

    // We need this to retrieve the object Beard from this Man object
    public Beard getBeard () {
        return beard;
    }
}
很抱歉,这个例子不太统一。。一开始我觉得很有趣

引入Beard对象只是为了展示一个更难的示例,我在处理继承和深度复制时遇到了这个示例。这样,当您使用聚合时,您将知道该做什么。如果您不需要访问任何对象,只需要访问原语,那么就可以使用类实例变量

public class Man extends Human {

    private String moustache;
    private double bicepDiameter;

    public Man (String aMoustache, double bicepSize) {
        this.moustache = aMoustache;
        this.bicepDiameter = bicepSize;
    }

    // This is the simple (no-object) deep copy block
    public Man (Man man) {
        this(man.moustache, man.bicepDiameter);
    }
}  

我真的希望这有帮助!快乐编码:)

文章可能重复“深度拷贝和浅层拷贝有什么区别?”“据我所知,这不是复制品。这篇文章彻底讨论了deepcopy,并展示了许多不同的例子,但我看不到任何一个是这种格式的。如果有重复的例子,我很乐意删除这个帖子。应该是:公众人物(Beard aBeard,String hairColor){super(hairColor);Beard=aBeard;}和这个(新的Beard(Man.getBeard().getBeardColor()),Man.getHairColor());