Copy constructor in Java

A copy constructor is used to copy the states(variables) of an object and assign it to the new object being created.

  • Java supports copy constructor and you have to explicitly define it.
  • Unlike C++, if you don’t define a copy constructor then Java will not provide a default copy constructor.

1. An Example

A copy constructor takes an object of the same class to which it belongs as an argument.

Output :

Notice that both the fruit objects have same values of variables. This was expected from a copy constructor.

If you comment the copy constructor, it would cause compilation error because the line  Fruit f2 = new Fruit(f1);   expects a copy constructor to be defined inside the class and it doesn’t find one because Java doesn’t provide a default copy constructor.

 


2. Copy constructor creates a deep copy of the variables

Note that a copy constructor creates a deep copy of the variables of the object. If you change the variables of one object created by a copy constructor, it won’t affect the other object.

Output :

Note that, after the variables of Student s2 were changed, it doesn’t affect the variables of Student s1.