Kindly clarify me for the following questions.
- Does
super.clone()perform Deep copying or shallow copying? - In the below example, why don’t we need class
CompositeObjCloneMeas cloneable? DoescObjwon’t be cloned while trying to cloneCloneMeobject?
Note: Even makingCompositeObjCloneMeas cloneable doesn’t have any impact on output. - Why the output is behaving like shallow copying (Not deep coppying) since program is setting primitive value(
setCObjValue = 100) of a class? (where primitive fields are deeply copied) -
Is it immutable Objects && primitives are inherently deeply copied?
class CloneMe implements Cloneable { private CompositeObjCloneMe cObj; public CloneMe() { cObj = new CompositeObjCloneMe(); } public void setCObjValue(int myOwnDt) { this.cObj.setObj(myOwnDt); } public int getCObjValue() { return this.cObj.getObj(); } //Clone public Object clone() throws CloneNotSupportedException { return super.clone(); } } class CompositeObjCloneMe {//implements Cloneable{ private int value = 20; public void setObj(int i){ value = i; } public int getObj(){ return value; } // public Object clone() throws CloneNotSupportedException{ // return super.clone(); // } } public class CloneTest { public static void main(String arg[]) { CloneMe realObj = new CloneMe(); try { CloneMe cloneObj = (CloneMe) realObj.clone(); realObj.setCObjValue(100); System.out.println(realObj.getCObjValue() + " " + cloneObj.getCObjValue()); } catch (CloneNotSupportedException cnse) { System.out.println("Cloneable should be implemented. " + cnse); } } }
OUTPUT: 100 100
1) javadoc to the rescue:
2) Because clone doesn’t call clone recursively. It’s a shallow clone. It just creates a new object with the same references as the original one, and copies of primitive fields.
3) I don’t understand what you mean. Primitive are not deeply copied. They don’t reference anything, so there’s nothing deep to copy.