#44 – Multiple References to the Same Object

If you assign a variable that points to a reference type to another variable of the same type, both variables end up pointing to the same object in memory.  This means that changing the contents of the object through the first reference results in changes that are also seen by the second reference.

The following code:

 Person p1 = new Person("Sean", 46);     // New Person object
 Person p2 = p1;                         // Points to same object

Results in this situation:

Also, if we change one of the properties of the Person object using the p2 reference, we see the same change when using p1. This confirms that both variables are pointing to the same object.

 p2.Age = 50;
 int age = p1.Age;       // Also now = 50

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment