Assigning Object Reference Variables

By: aathishankaran Printer Friendly Format    

            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.





Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. Thanks, cleared the situation!!
View Tutorial          By: alex at 2010-03-23 16:16:49

2. its not solve my problem.i.e
the concept is

View Tutorial          By: murli at 2010-10-02 23:23:11

3. finally i got it !!! thanks a lot!!! you really he
View Tutorial          By: maher at 2010-11-11 02:44:07

4. This was simple and clear. Thanks!
View Tutorial          By: Evik James at 2011-08-02 12:17:54

5. i have asked for refercing the object of main clas
View Tutorial          By: deepesh at 2012-08-20 10:33:58

6. Thanks, It's exactly. A my friends has the same is
View Tutorial          By: Slim at 2012-09-29 02:52:12

7. It is clear but at the starting code there is a wr
View Tutorial          By: Kiranmoy Pradhan at 2015-08-20 21:55:15

8. I see two mutually incompatible statements in the
View Tutorial          By: Deepak Mohan at 2015-12-22 01:50:29