I am a bit new to these two methods of copying one object into the other. I am confused and unable to spot out the major difference between deep copy and shallow copy.. I ha
This is neither a shallow nor a deep copy, this is a reference copy.let me explain: there are 2 types of variables : value types and reference types.
a value type is a (named) location in computer memory that hold the actual value of the variable. for example: int is a value type, so when you write this line of code:
int MyInt = 5;
when this line of code get executed the runtime will find a location in the RAM and write the value 5 in it. so if you search that location you will find an actual value of 5.
a reference type -in contrast- is a (named) location in memory that does not actually hold the value of the variable but hold the location of memory where that value exists. as an example suppose you wrote the following code:
MyClass myObject = new MyClass();
what happens is that the virtual machine (runtime): 1- look and find an available location in memory , create an instance of the MyClass class. lets say that the location of that object happened to be at byte # AA3D2 in RAM.
2- find a location in memory and create a reference of type MyClass (a reference is an "arrow" that point to a location in memory),name it "myObject" and store the value AA3D2 in it.
now if you look at the "myObject" variable you will find not the class instance but you will find AA3D2 which represent the location of memory that hold that class instance.
now lets examine the code given my the OP:
A ob1 = new A();
this will make a variable called ob1 ,create instance of the A class and store the location of that class in ob1
ob1.a = 10;
ob1.display();
this will change the variable a which is inside the A class. it then invoke the display() method
A ob2 = new A();
here it create a variable called ob2 ,create an instance of the class A and assign its location to ob2.
by now you have in memory 2 class instances of A and 2 variables each pointing to one of them. now here is the interesting part : ob2 = ob1;
the variable ob2 is assigned the value of the variable ob1. because ob1 contain the memory location of the first instance of A ,now both ob1 and ob2 point to the same location in memory. doing anything using one of them is exactly doing the same thin with the other.
ob2 = ob1 means you are copying the reference.