But using a clone method is more difficult compared to a copy constructor, due to the following reasons:ġ. Difference Between Java Copy Constructor and Clone() Method:Ĭlone() is also a method using which we can create a duplicate copy of a pre-existing object. So, we can see why a copy constructor is an important concept to write optimal code. Now, imagine if there are 50 such variables how hard it will be to copy each variable separately.
JAVA CONSTRUCTOR EXAMPLE CODE
So, we can clearly see that the size of the code increased considerably for only 2 variables. ("Copied Name of Intern: "+ I2.printName()) To understand the advantage of a copy constructor, let us try to copy an object without using a copy constructor.Ĭode for creating a copy of an object without using Copy Constructor: package 圜onstructor Copy Constructor is easier when there are several fields in it.We can change the copied object without hampering the original object.In Copy Constructor there is no need for Type Casting.The copy constructor can be used to change the state of a variable from final to normal.ID of Intern: 1 Name of Intern:Arka Advantages of Using Copy Constructor in Java ("ID of Intern: "+ I.showID()+ " Name of Intern:"+ I.showName()) Interns(Interns interns)//copy constructor
Interns(int id, String name)//parameterized constructor This.InternDate = new Date(()) //Deep CopyĬode to Explain the working of Copy Constructor: package 圜onstructor To copy mutable type data, we have to create a deep copy instead of a shallow copy which we did in the previous example.Ĭode to understand Mutable data with copy constructor: public class Interns Step 2: Using getters copy each variable of the copied object to the new instances. Public Interns(Interns interns)//copy constructor Make sure that the object belongs to the same class. Step 1: We have to create a constructor that takes an object as a parameter. The steps to create a copy constructor are as follows: Sometimes we might be required to use a copy of an object with minor changes, without reflecting it to the original one, for such scenarios a copy constructor is essential. The main purpose of a copy constructor is to create a copy of an object. Why is it required to use Java Copy Constructor? In C language, the copy constructor is declared automatically, but in Java, we have to create the method separately.
It is a special type of constructor that returns a duplicate copy of another object. What is a Copy Constructor in Java?Īs the name suggests, Copy Constructor is used to create a copy of a previously existing object present in the class.
Other than these two Constructors, Java also supports Copy Constructors, we will discuss it in detail now.