A copy constructor is a constructor that creates a new object as a copy of an existing object of the same class. In Java, although this concept is not part of the language structure (unlike in C++), we can simulate its functionality by creating a constructor that accepts an object of the same class as a parameter.
Here is a specific example to illustrate how to implement a copy constructor in Java:
Assume we have a class named Student with two properties: name and age for students:
javapublic class Student { private String name; private int age; // Default constructor public Student() {} // Parameterized constructor public Student(String name, int age) { this.name = name; this.age = age; } // Copy constructor public Student(Student other) { this.name = other.name; this.age = other.age; } // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public static void main(String[] args) { Student original = new Student("John", 20); Student copy = new Student(original); System.out.println("Original: " + original.getName() + ", " + original.getAge()); System.out.println("Copy: " + copy.getName() + ", " + copy.getAge()); } }
In this example, the Student class has a copy constructor that accepts another Student object as a parameter and initializes the newly created object using the properties of the given object. This ensures that the new object is an exact copy of the original object.
One main benefit of using a copy constructor is that it allows explicit control over the copying process when duplicating objects, especially when the copying involves more than a shallow copy (i.e., not only copying values but also copying other objects referenced by the object).
It also facilitates returning class instances from methods or passing them as parameters to other methods without the risk of modifying the original object.