World's most popular travel blog for travel bloggers.

Assigning Object Reference Variables

, , No Comments

Assigning Object Reference Variables


Object reference variables act differently than you might expect when an assignment takes place. It has been explained in this article. You can take an example of following code. Here an object t1 is created for Test class and another object T2 is assigned for the t1 then what do you think the following fragment does?
            Test t1 = new test ();
            Test t2 = t2;
            You might think that t2 is being assigned a reference to a copy of the object referred to by t1. That is, you might think that t1 and t2 separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, t1 and t2 will both refer to the same object. The assignment of t1 to t2 did not allocate any memory or copy and part of the original object. It simply makes t2 refer to the same object, as does t1. Thus, any changes made to the object through t2 will affect the object to which t1 is referring, since they are the same object.
            This situation is depicted here:
t1

Width
Height
Depth
Test Object
t2

    Although t1 and t2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to t1 will simply unhook t1 from the original object without affecting the object or affecting t2.
 For example,
 Test t1 = new test ();
Test t2 = t1;
//…
t1 = null
             Here, t1 has been set to null, but still points to the original object.

0 comments:

Post a Comment

Let us know your responses and feedback