Losing object refference/How object refference changes


We know object(instance of a class) is refference type.  But sometimes we found that we create object assigne some value and later when we go to use this object we don’t get the assigned value this happens because of some mistakes that we do unconciously. The below example shows how that happens :

             Class1 obj1 = new Class1();

What happens here  a new object is created in memory in other words memory is allocated for the members of Class1 and obj1 got a refference no to point that.

Suppose obj1 got refference no “Refference-1”

            obj1.val1 = 5;
            obj1.val2 = 10;

            Class1 obj2 = obj1;

So, obj2 got refference no “Refference-1” (Both obj1 and obj2 have same refference no)

            obj2.val1 = 25;

 At this stage we know that both obj1 and obj2 have same refference no  so any changes between these object will affect other so values of obj2.val1 and obj1.val1 would be 25.

             obj1 = new Class1(); 

 What happens here  a new object is created in memory in other words memory is allocated for the members of Class1 and obj1 got a new refference no. Suppose obj1 got new refference no “Refference-2”

 So now obj1 and obj2 have different refference no and any changes between them will not affect other.

At this stage refference no of obj1 is “Refference-2” and of obj2 is “Refference-1”

             obj1.val2 = 15; this will not affect the value of obj2.val2.

at this stage the value of  obj2.Val2 would be 10 and the value of obj1.val2 would be 15

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: