Shallow copy means a “copy” of an object with same values of their attributes whether primitive or reference values.
While performing shallow copy is it necessary to “create a new instance” ? as:
public class A {
int aValue;
B bObj;
...
public A createShallow(A a1Obj) {
A aObj = new A();
aObj.aValue = a1Obj.aValue;
aObj.bObj = a1Obj.bObj;
return aObj;
}
}
Or copy by assignment is also considered as shallow copy:
B b = new B(10);
A a = new A(1, b);
A a1 = a;
This article at wikipedia defines shallow copy as reference variables sharing same memory block. So according to this copy by assignment will also be a shallow copy.
But is not it a variables pointing to same object instead of “copy” of an Object ?
Yes, you must create an instance to create a copy (either
shallowordeep) of your object. Just doing the assignment of reference just creates acopy of referencewhich points to the same instance.You have used a
non-static methodthat is creating acopy. But generally I prefer two ways: –Either use a
copy-constructor: –And use it like: –
Or, use a
public static methodwhich takes an instance and returns a copy of that.