As per definition:
A shallow copy is one in which we only copy values of fields from one object to another. They are different objects, but the problem is that when we change any of the original address' properties, this will also affect the shallowCopy‘s address.
I tried to see if value of object 1 and object 2 becomes same so tried following and not able to do so.
public class TestClone implements Cloneable {
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Main Program:
package com.test;
public class MainTestClone {
public static void main(String[] args) throws CloneNotSupportedException {
TestClone clone = new TestClone();
clone.setA("RABA");
TestClone clone2 = (TestClone) clone.clone();
System.out.println(clone.getA());
System.out.println(clone2.getA());
System.out.println("---------------------------");
clone.setA("DABA");
System.out.println(clone.getA());
System.out.println(clone2.getA());
System.out.println("---------------------------");
clone2.setA("Clone2 RABA DABA");
System.out.println(clone.getA());
System.out.println(clone2.getA());
}
}
Output:
RABA
RABA
---------------------------
DABA
RABA <--- It does not change to DABA
---------------------------
DABA <--- No Changes here
Clone2 RABA DABA