Copying objects

Class under consideration

We will use the following class for this discussion.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Rectangle {
	public double width, height;	
    
   public Rectangle(double w, double h) {
    	width = w;
    	height = h;
   }
    
   public Rectangle(Rectangle other) {
    	width = other.width;
    	height = other.height;
   }
}

Copying using assignment operator (=)

When you copy an object into another using an assignment operator (=), the reference of the source object is copied into the destination object.

1
2
Rectangle source = new Rectangle(1.2, 2.5);
Rectangle destination = source;

Given that the object source holds the reference to the instance, that reference is copied into object destination. Now there are two objects referring to the same instance.

 

 

If you change the value of the instance variables of either source or destination, the other object will be affected.

1
destination.width = 666.66;
 

 

Copying using copy constructor

Instead of assigning an object to another object, you can copy each instance variable of an object into corresponding instance variables of other objects using the copy constructor.

1
2
Rectangle source = new Rectangle(1.2, 2.5);
Rectangle destination = new Rectangle(source); //invoke copy constructor
 

 

If you change the value of the instance variables of either source or destination, the other object will NOT be affected.

1
destination.width = 888.88;
 

 

When copy constructor is not defined

When the copy constructor is not defined, you can always perform equivalent action by copy each instance variable individually as,

1
2
3
4
Rectangle source = new Rectangle(1.2, 2.5);
Rectangle destination = new Rectangle(); 
destination.width = source.width;
destination.height = source.height;