Define Copy Constructor in Java
In Java, a copy constructor is a special type of constructor that is used to create a new object as a copy of an existing object. It takes an instance of the same class as a parameter and initializes the new object with the values of the fields from the passed object. This is particularly useful when you want to create a duplicate of an object while ensuring that the new object has its own separate copy of the data.
Java does not provide a built-in copy constructor like C++, but you can define one manually in your class. Here’s how you can implement a copy constructor in Java:
class Person {
private String name;
private 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;
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Method to display person details
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Create an original object
Person original = new Person("Alice", 30);
original.display();
// Create a copy of the original object using the copy constructor
Person copy = new Person(original);
copy.display();
}
}
Person
class has a regular constructor that initializes the name
and age
fields.Person
object as a parameter and copies its name
and age
fields to the new object.main
method, an original Person
object is created, and then a copy of that object is created using the copy constructor.If your class contains mutable objects (like arrays or other objects), you may need to implement a deep copy to ensure that the copied object does not share references with the original object.