Copy Constructor in Java – A Complete Guide with Examples

Updated on July 23, 2024

Article Outline

In Java, constructors are the special methods that initialize objects. They have the same name as the class and are invoked automatically when an object of the class is created. Although there are many types of constructors, our main focus is on copy constructors. It is a unique constructor that creates a clone of an object.

What is a Copy Constructor in Java?

A copy constructor is a special constructor that creates a new object by copying values from an existing object of the same class. It copies the values of all member variables, including primitive types, arrays, and object references. It is specially used for creating deep copies of an object, which ensures any modification made to the copied object will not reflect the original object.

 

A copy constructor accepts an object as an argument and initializes a new object with the same state as provided. This constructor can’t be inherited and needs to be defined in each subclass. It provides flexibility, reliability, and maintainability to the codebase by providing customized copying options.

 

Example: Let’s see an example to understand the concept of copy constructor.

// defining a class public class Student { // class variables private String name; private int age; // defining parameterised constructor public Student(String name, int age){ this.name = name; this.age = age; } // defining copy constructor public Student(Student s){ this.name = s.name; this.age = s.age; } // creating display function public void display(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); } public static void main(String[] args){ // create a new object of class Person Student s = new Student("Mohan", 15); // display original student details System.out.println("Displaying the original object"); s.display(); // Display copied student details System.out.println("Displaying the copied object"); Student copiedStudent = new Student(s); copiedStudent.display(); } }

Output:

Displaying the original object Name : Mohan Age : 15 Displaying the copied object Name : Mohan Age : 15
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Types of Copy Constructors in Java

Generally, there are two types of copy constructors in Java: Default copy constructor and Deep copy constructor. Let’s discuss each in detail.

Default Copy Constructor:

It is the normal copy constructor provided by Java. It performs a shallow copy of an object’s fields, which means it copies the object field references rather than creating a new object itself.

Example:

package com.example.demo; // Example of Default Copy Constructor // defining a class public class Person { // class variables private String name; private int age; // defining parameterised constructor public Person(String name, int age){ this.name = name; this.age = age; } // creating display function public void display(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); } public static void main(String[] args){ // create a new object of class Person Person p = new Person("Mohan", 15); // display original person details System.out.println("Displaying the original object"); p.display(); // defining a new object Person p1 = new Person("Rohan", 20); // copying p to p1 p1 = p; // performs a shallow copy // Display copied person details System.out.println("Displaying the copied object"); p1.display(); } }

Output:

Displaying the original object Name : Mohan Age : 15 Displaying the copied object Name : Mohan Age : 15

Deep Copy Constructor:

For creating a deep copy constructor, we need to manually copy each object field to ensure new instances of mutable objects are created.

 

Example:

// Example of Deep Copy Constructor // defining a class public class Person { // class variables private String name; private int age; // defining parameterised constructor public Person(String name, int age){ this.name = name; this.age = age; } // defining copy constructor public Person(Person p){ this.name = p.name; this.age = p.age; } // creating display function public void display(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); } public static void main(String[] args){ // create a new object of class Person Person p = new Person("Java", 45); // display original person details System.out.println("Displaying the original object"); p.display(); // Display copied person details System.out.println("Displaying the copied object"); // Using the deep copy constructor Person copiedPerson = new Person(p); copiedPerson.display(); } }

Output:

Displaying the original object Name : Java Age : 45 Displaying the copied object Name : Java Age : 45

Advantages of Copy Constructor in Java

Below are some benefits of using the copy constructor.

 

  • Control Copying: It provides developers with control over how to copy objects. In addition, it allows customization as per the desired requirements.
  • Safe Object Initialization: It helps to initialize new objects safely by preventing the side effects from modifying the original object.
  • Flexibility: It provides flexibility to implement custom copy behaviour and accommodate multiple scenarios and use cases.
  • Efficient: It is more efficient than other copying methods, as it has direct access to object members.
  • Support Deep Copy: It allows the creation of deep copy by ensuring nested objects are duplicated accurately.

Disadvantages of Copy Constructor in Java

Below are some challenges of using the copy constructor.

 

  • Limited Accessibility: It can only access the accessible members of the object, which limits its usability in many scenarios.
  • Manual Implementation: It requires manual implementation within classes, which increases development efforts and the risk of errors.
  • No Inheritance: It can’t be inherited and needs to be explicitly implemented in the class where copying is needed.
  • Not Serializable: The objects created using the copy constructor are not serializable. They require additional effort for serialization and deserialization.
  • No Cloning Support: It doesn’t have built-in support for cloning objects.

Applications of Copy Constructor in Java

  • It created a new object by copying the existing state of the original object, which facilitates the creation of deep copies. It is specifically useful when handling complex objects containing nested structures.
  • It ensures safe object initialization. It makes sure the new object created is independent of the original, therefore preventing unintended side effects.
  • It is used in special cases like cloning objects, implementing design patterns, and facilitating object serialization and deserialization.
  • It provides flexibility, reliability, and maintainability to the codebase by providing customized copying options.

Comparison between Copy Constructor and the clone() Method

Here is the tabular comparison between the Copy Constructor and the clone() method,

 

Copy Constructor clone() Method
It is a special constructor that creates a new object by copying values from the existing object of the same class. It is a method defined under the Cloneable interface that creates a new object as a clone of the original object.
It can be accessed from any class within the same package or subclass. It is only accessible to classes that implement a Cloneable interface.
It throws expectations as per the defined program logic. It requires handling of checked exceptions and can throw a CloneNotSupportedException.
It returns a new object of the same class. It returns an object, which requires casting to the appropriate type.
It requires manual implementation for deep copying. By default, It supports shallow copy and requires manual implementation for deep copying.
It is more efficient as it has direct access to members. It is less efficient because of method invocation and casting.
It offers flexibility for handling complex copy scenarios. It can be customized by overriding the clone() method.
It doesn’t require any specific interface. Whereas, the class needs to implement a Cloneable interface for this method.
This constructor can’t be inherited and needs to be defined in each subclass. The clone() method can be inherited.
Copy constructors can access all public, protected, and private fields. It can access only public and protected fields.

Conclusion

This concludes our discussion on what copy constructors are in Java. We discussed its types, applications, advantages, and disadvantages. We see different types of copy constructors with proper implementation and also compare them with the clone() method to get a better understanding of the topic.

FAQs
In OOPS, a copy constructor is a special constructor that creates a new object by copying its existing state. It provides the most fitting way to initialize objects through duplication.
The Copy Constructor is used when objects need to be duplicated while maintaining their state integrity or when objects are initialized based on existing instances.
No. By default, a copy constructor only creates a shallow copy. In order to create a deep copy, we need to handle deep copying logic within the copy constructor.
A regular constructor is used to initialize a new object, whereas a copy constructor creates an object by copying its existing state.

Updated on July 23, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved