Last Updated: 21 September, 2024
In Java, a copy constructor is a special type of constructor that is used to create a new object using an existing object of the same class.
Copy constructor is used if we need to copy a complex object that has many fields or when we need to create a deep copy of an existing object.
Java does not implicitly provide the facility of a copy constructor as in the 'C' language.
Copy Constructor Syntax:
Copy constructors are one of the strongest features for creating copies of objects in Java. They can be used to create shallow copies or deep copies of objects, depending on our needs.
To create a copy constructor, we simply need to define a constructor that takes an object of the same class as its argument. For example, the following example shows a copy constructor for a class named Student:
In the above example, to use the copy constructor, we created a new instance of the Student class and passed an existing Student object to the constructor.
After executing the above code, the student2 object will be a copy of the student1 object. This means that the student2 object will have the same student name and roll as the student1 object. However, the student2 object will be a separate object from the student1 object.
See the output of the program after execution.
Output
Parameterized constructor is called.
student1 - Student Roll No. : 15
student1 - Student Name : Shiyanshi Sona
Copy constructor is called.
student2 - Student Roll No. : 15
student2 - Student Name : Shiyanshi Sona
The Copy constructor and the Object class's clone() method are both used to create an object from the existing object of the class.
In comparison to the clone() method, the copy constructor is simpler and more efficient for creating a copy of an existing object. Let's take a look at the table below to see how they differ.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com