Patrick B. answered 07/21/19
Math and computer tutor/teacher
Shallow copy: a bitwise copy of the object...
If X = Y then they both point to the same object.
If x changes, so does Y. If Y changes, so does X.
Deep copy: The entire object INCLUDING the fields, dynamically allocated
data members, and anything else referenced by the object
are copied into a separate memory location
In this case if X is deep copied into Y, then if X changes Y is NOT changed.
If Y changes, X stays the same. If one disappears, the other is still valid in memory.
The proper term is CLONING. This is typically done with a COPY constructor.
Here is some sample code:
class DataRec
{
private String strCode;
private long longIntNum;
private double flAmt;
//constructor
DataRec( String str, long L, double flX)
{
if (str != null)
{
strCode = new String(str);
}
else
{
strCode = null;
}
longIntNum = L;
flAmt = flX;
}
//public getters and setters
public String getStr() { return(strCode); }
public long getLong() { return(longIntNum); }
public double getAmt() { return(flAmt); }
public void setStr( String newStr) { strCode = new String(newStr); }
public void setLong( long L) { longIntNum = L; }
public void setAmt( double flX) { flAmt = flX; }
public DataRec ShallowCopy( DataRec X)
{
DataRec Y = X; //just copies the object reference
return(Y);
} //shallowCOpy
//copy constructor
DataRec(DataRec X)
{
//copies ALL of the data into this instance
String str = X.getStr();
if (str!=null)
{
this.strCode = new String(str);
}
else
{
this.strCode = null;
}
this.longIntNum = X.getLong();
this.flAmt = X.getAmt();
} //copy constructor
public DataRec DeepCopy( DataRec X)
{
DataRec Y = new DataRec(X);
return(Y);
} //deepCopy
public void Output(String debugMsg)
{
System.out.println("***********************************");
System.out.println(debugMsg);
System.out.println("***********************************");
System.out.println(" StrCode = >" + this.getStr() +"<");
System.out.println(" longIntNum = " + this.getLong() );
System.out.println(" Amt = " + this.getAmt() );
} //output
public static void main(String args[])
{
DataRec copyDummy = new DataRec(null,0,0);
DataRec dataRec1 = new DataRec("DataRec1",12345,3.45f);
DataRec dataRec2 = copyDummy.ShallowCopy(dataRec1);
dataRec1.Output( "DataRec1 before the change");
dataRec2.Output( "DataRec2 before the change");
dataRec2.setAmt(3.33f);
dataRec1.setLong(54321);
dataRec1.Output( "DataRec1 after the change");
dataRec2.Output( "DataRec2 after the change"); //they both shall be DataRec1, 54321, 3.33
DataRec dataRecA = new DataRec("data Rec A",98765,35.42f);
DataRec dataRecB = copyDummy.DeepCopy(dataRecA);
dataRecA.Output(" DataRec A before the change");
dataRecB.Output(" DataRec B before the change");
dataRecB.setAmt(42.35f);
dataRecA.setLong(711333);
dataRecA.Output(" DataRec A after the change"); //data Rec A, 711333. 35.42
dataRecB.Output(" DataRec B after the change"); //data Rec A, 98765, 42.35
} //main
} //class