0
0
JavaConceptBeginner · 3 min read

What is Copy Constructor in Java: Explanation and Example

A copy constructor in Java is a special constructor used to create a new object by copying an existing object's values. It takes another object of the same class as a parameter and duplicates its fields to the new object.
⚙️

How It Works

Think of a copy constructor like making a photocopy of a document. Instead of writing everything again, you just copy the original. In Java, a copy constructor takes an existing object and creates a new object with the same data.

This means the new object starts with the same values as the original, but it is a separate object in memory. Changes to one won't affect the other. This is useful when you want to duplicate objects safely without mixing their data.

💻

Example

This example shows a simple class with a copy constructor that duplicates the values of an existing object.

java
public class Person {
    String name;
    int age;

    // Regular constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Copy constructor
    public Person(Person other) {
        this.name = other.name;
        this.age = other.age;
    }

    public void display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }

    public static void main(String[] args) {
        Person original = new Person("Alice", 30);
        Person copy = new Person(original); // Using copy constructor

        original.display();
        copy.display();
    }
}
Output
Name: Alice, Age: 30 Name: Alice, Age: 30
🎯

When to Use

Use a copy constructor when you want to create a new object that starts with the same data as an existing one but remains independent. This is helpful when:

  • You want to avoid accidental changes to the original object.
  • You need to pass a copy of an object to a method or store it separately.
  • You want to implement cloning behavior without using the clone() method.

For example, in games, copying a character's state to save progress or in applications where you want to keep original data safe while working on a copy.

Key Points

  • A copy constructor creates a new object by copying an existing object's data.
  • It helps avoid shared references that can cause bugs.
  • Java does not provide a default copy constructor; you must define it yourself.
  • It is an alternative to the clone() method for copying objects.

Key Takeaways

A copy constructor duplicates an object’s data into a new, separate object.
It prevents changes in one object from affecting the other.
Java requires you to write your own copy constructor; it is not automatic.
Use it when you want safe object copying without using clone().