What is a Copy Constructor :
*A copy constructor is a special constructor that creates a new object by copying values from an existing object of the same class.
* 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.
Why used to copy constractor :
In Java, a copy constructor is used to create a new object as a copy of an existing object.
Ex
class Student {
int id;
String name;
// Constructor (original data)
Student(int i, String n) {
id = i;
name = n;
}
// Copy Constructor (copy panrathu)
Student(Student s) {
id = s.id;
name = s.name;
}
void show() {
System.out.println(id + " " + name);
}
}
Student s1 = new Student(101, "Ravi"); // Original object
Student s2 = new Student(s1); // Copy object
s1.show(); // 101 Ravi
s2.show(); // 101 Ravi
Reffer ::
https://herovired.com
Top comments (0)