Copy Constructor: Sometimes a programmer wants to create an exact but separate copy of an existing object so that subsequent changes to the copy should not alter the original or vice versa. This is made possible using the copy constructor. It takes the object of the class as a reference to the parameters. This means that whenever we initialize an instance using value of another instance of same type, a copy constructor is used.
A copy constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument. This constructor takes a single argument whose type is that of the class containing the constructor.
class Rectangle
{
int length;
int breadth;
//constructor to initialize length and bredth of rectang of rectangle
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
System.out.println("Copy Constructor Invoked");
length = obj.length;
breadth= obj.breadth;
}
//method to calcuate area of rectangle
int area()
{
return (length * breadth);
}
}
//class to create Rectangle object and calculate area
class CopyConstructor
{
public static void main(String[] args)
{
Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect= new Rectangle(firstRect);
System.out.println("Area of First Rectangle : "+ firstRect.area());
System .out.println("Area of First Second Rectangle : "+ secondRect.area());
}
}
The statement,
Rectangle firstRect = new Rectangle(5,6);
creates a Rectangle object and invokes the constructor Rectangle (int l,int b) which initializes values length and breadth with values 5 and 6 respectively and returns the reference to firstRect variable.
The statement,
Rectangle secondRect = new Rectangle (firstRect);
invokes a copy constructor
Rectangle(Rectangle obj)
and initializes the instance variables length and breadth of the newly created Rectangle object and returns its reference to the secondRect variable.
One may think, as in C++ the copy constructor can be invoked using the statement,
Rectangle secondRect = firstRect;
but this is not so. Here the variable secondRect references to the same object as firstRect. No new object is created.