#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
Advertisements

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

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: