Saad Khan
Saad Khan

Reputation: 313

What happens when an object is assigned to another object

public class DrumKitTestDrive {
/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Echo e1 = new Echo();
    Echo e2 = new Echo();
//      **e2 = e1;**

    int x=0;
    while( x < 4 ){
        e1.hello();
        e1.count = e1.count + 1;
        if(x==3){
            e2.count = e2.count + 1;
        }
        if(x>0){
            e2.count = e2.count + e1.count;
        }
        x = x + 1;
    }
    System.out.print(e2.count);
    }
}

class Echo {
    int  count = 0;

    void hello(){
        System.out.println("Hellooooo....");
    }
}

The output of this code will be:

Hellooooo....
Hellooooo....
Hellooooo....
Hellooooo....
10

But if I remove the comments from // e2= e1; when I run the code the system will print 24 instead of 10. I don't understand why is it so?

What I understand is the system will just copy the values of e1 instance into e2 instance. And if the system will do so, the result shall remain the same because both objects are of the same class.

Upvotes: 10

Views: 55765

Answers (4)

Jake Peralta
Jake Peralta

Reputation: 547

Try creating constructor for method Echo, with another object as parameter. And assign values of parameter object to this object. i.e. '''

Echo(Echo echo) {
  this.count = echo.count;
}

'''

And then create the node e2 as:

Echo e2 = new Echo(e1);

Upvotes: 0

pb2q
pb2q

Reputation: 59617

What I understand is the system will just copy the values of e1 instance into e2 instance.

No, when you do e2 = e1 you're copying object references - you're not making a copy of the object - and so the variables e1 and e2 will both point to the same object.

And so when you do your increments, they're all incrementing the same count field.

It's only without the assignment e2 = e1 that the increments are happening on two different instances.

Upvotes: 23

Tony R
Tony R

Reputation: 11524

Assigning one object to another just assigns the object reference (a pointer more or less). It does NOT copy member variables etc.

You need to read about cloning. From the first paragraph of the wiki for Java clone():

In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality.

Upvotes: 5

Rajesh J Advani
Rajesh J Advani

Reputation: 5710

This is one of the basic principles of Java. Each variable, is just a handle to some object. Executing

e1=e2

doesn't copy the values of the objects, it points both handles to the second object that was created. The first Echo object that you instantiated is now not referenced at all, and will be garbage collected the next time gc runs.

Upvotes: 7

Related Questions