A copy constructor is a parameterized constructor and it can be used when we want to copy the values of one object to another.
class Employee { int id; String name; Employee(int id, String name) { this.id = id; this.name = name; } Employee(Employee e) { id = e.id; name = e.name; } void show() { System.out.println(id + " " + name); } public static void main(String args[]) { Employee e1 = new Employee(001, "Aditya"); Employee e2 = new Employee(e1); e1.show(); e2.show(); } }
In the above code, e1 is passed as an argument to the second constructor. Thus values of e1 are copied into object e2.
1 Aditya 1 Aditya