Object references (II)

3 March 2008

This post is in continuation of Object references (I). Please read that before this one.

Now lets try to understand what happened in the example given in Object references (I). We created an object called obj1 of class Student using constructor with 2 parameters. When we called a method called testMe(…) which takes an object of class Student as argument. In Java, objects are passed by reference. So when we displayed the contents of object a (in testMe) method, we got the same contents as of obj1. No worries until now.

In testMe(…), we altered the name attribute of object a, and displayed the contents, we got the altered contents. No problem so far. When we displayed the contents of object obj1 in main method, we noticed that the contents of obj1 has been changed. How this happened???

Actually the objects are passed by reference in methods. So object obj1 and object a, both are referring to the same.

Now lets do one more experiment. Review the code below:

Student obj1 = new Student(1, "Laiq");
 
System.out.println("obj1: ");
obj1.showAll();
 
Student obj2 = new Student(2,"Dave");
 
System.out.println("obj2: ");
obj1.showAll();
 
obj1 = obj2;
obj1.setName("Toni");
 
System.out.println("obj1: ");
obj1.showAll();
 
System.out.println("obj2: ");
obj2.showAll();

Output:

obj1: 
id: 1
name: Laiq
obj2: 
id: 1
name: Laiq
obj1: 
id: 2
name: Toni
obj2: 
id: 2
name: Toni

The output shows interesting results. One you use equal operator to assign one object to another object, then both refer to the same object in memory, but with different name.

del.icio.us:Object references (II)  digg:Object references (II)  spurl:Object references (II)  wists:Object references (II)  simpy:Object references (II)  newsvine:Object references (II)  blinklist:Object references (II)  furl:Object references (II)  reddit:Object references (II)  fark:Object references (II)  blogmarks:Object references (II)  Y!:Object references (II)  smarking:Object references (II)  magnolia:Object references (II)  segnalo:Object references (II)  gifttagging:Object references (II)

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Object references (II)

Leave a Reply