0

I'm cloning one object into another object and then trying to change only two parameters in new object. But still the original object is getting changed. I just want both copies should be separate. Here is my code

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

Both cases it's printing first object only.

Clone method in group class

 Protected Object clone() throws CloneNotSupportedException {
     return super.clone();
 }
Sentry
  • 4,102
  • 2
  • 30
  • 38
Syed
  • 2,471
  • 10
  • 49
  • 89

2 Answers2

1

The clone() in class Object does only shallow copy, instead you need to check how to do deep cloning

Community
  • 1
  • 1
ravthiru
  • 8,878
  • 2
  • 43
  • 52
  • You can use commons-lang SerializationUtils , Group g2 = (Group) SerializationUtils.serialize(g1); But all classes should be Serializable – ravthiru Sep 26 '16 at 05:33
1

By overriding cloning method you will create a copy of your object.

Please find below example:

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();
        }
    }
}
Amit Bhoraniya
  • 621
  • 3
  • 14