VOOZH about

URL: https://www.geeksforgeeks.org/java/copy-constructor-in-java/

⇱ Copy Constructor in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Copy Constructor in Java

Last Updated : 15 Jun, 2026

A Copy Constructor in Java is a constructor that creates a new object by copying the values of an existing object of the same class. Unlike C++, Java does not provide a default copy constructor, so it must be explicitly defined by the programmer.

  • Helps create independent copies of objects.
  • Can be used for shallow or deep copying.
  • Improves code readability and object management.

Syntax

class ClassName {
ClassName(ClassName obj) {
// Copy data members
}
}

 Steps to Implement a Copy Constructor

  • Create a class.
  • Define instance variables.
  • Create a parameterized constructor.
  • Create a constructor that accepts an object of the same class.
  • Copy the values of the object into the current object.
  • Use the copied object whenever a duplicate object is required.
  • For object references, perform deep copying if complete independence is

Example 1: Copying a Student Object


Output
Original Object:
Name: John
Age: 20

Copied Object:
Name: John
Age: 20

Explanation: In this example, s1 is the original object created using the parameterized constructor. The statement Student s2 = new Student(s1); invokes the copy constructor, which copies the values of name and age from s1 to s2. As a result, s2 becomes a separate object containing the same data as s1.

Example 2: Copy Constructor with Complex Numbers


Output
Copy constructor called
(10.0 + 15.0i)

Explanation: In this example, c1 is created using the parameterized constructor. The statement Complex c2 = new Complex(c1); invokes the copy constructor, which copies the values of re and im from c1 to c2. The statement Complex c3 = c2; does not create a new object; it only copies the reference. Therefore, only the creation of c2 uses the copy constructor.

Example 3: Invalid Constructor Call

Output:

👁 Image

Now, in the above code, the line calling the function with the object c1 as the parameter will give the error as the type of the parameter in the constructors is of 'double' type while the passed content is of 'object' type.

Advantages of Copy Constructor

  • Creates a duplicate object easily.
  • Improves code readability and maintainability.
  • Preserves the original object while creating a copy.
  • Useful when working with immutable or complex objects.
  • Can be customized for deep copying to avoid shared references.
Comment
Article Tags:
Article Tags: