Syed Syed - 2 months ago 6
Java Question

Overriding cloned object completely in java

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

Answer

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