在java中完全覆盖克隆对象

时间:2016-09-26 05:17:05

标签: java clone

我将一个对象克隆到另一个对象中,然后尝试仅更改新对象中的两个参数。但是原始对象仍然在变化。我只想要两份副本分开。这是我的代码

Subgroup sg1 = new Subgroup();
sg1.setFname("Vali");
sg1.setMname("Sheik");
sg1.setLname("Sha");
Group g1 = new Group();
g1.setSg(sg1);
try { 
     Group g2 = (Group) g1.clone();
     Subgroup sg1 = g2.getSg();
     sg2.setFname("parvez");
     sg2.setMname("syed");
     sg2.setLname("khan");
     g2.setSg(sg2);
     System.out.println(g1);
     System.out.println(g2);
} catch (CloneNotSupportedException e) {  
     e.printStackTrace();
}

两种情况下它都只打印第一个对象。

组类中的克隆方法

 Protected Object clone() throws CloneNotSupportedException {
     return super.clone();
 }

2 个答案:

答案 0 :(得分:1)

类Object中的clone()只执行浅层复制,而是需要检查如何执行deep cloning

答案 1 :(得分:1)

通过重写克隆方法,您将创建对象的副本。

请在下面找到示例:

<强> Subgroup.java

public class Subgroup {

    private String fname;
    private String mname;
    private String lname;

    //getter-setter

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Subgroup sg = new Subgroup();
        sg.setFname(this.fname);
        sg.setMname(this.mname);
        sg.setLname(this.lname);
        return sg;
    }

     //to-string

}

<强> Group.java

public class Group {

    private Subgroup sg;

    //getter-setter

    public Object clone() throws CloneNotSupportedException {
        Group g = new Group();
        g.setSg((Subgroup) this.sg.clone());
        return g;
    }
    //to-string

}

TestMain.java

public class TestMain {

    public static void main(String[] args) {
        Subgroup sg1 = new Subgroup();
        sg1.setFname("Vali");
        sg1.setMname("Sheik");
        sg1.setLname("Sha");
        Group g1 = new Group();
        g1.setSg(sg1);
        try {
            Group g2 = (Group) g1.clone();
            Subgroup sg2 = g2.getSg();
            sg2.setFname("parvez");
            sg2.setMname("syed");
            sg2.setLname("khan");
            g2.setSg(sg2);
            System.out.println(g1);
            System.out.println(g2);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}