What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

  1. //Java program to initialize the values from one object to another
  2. class Student6{
  3.     int id;
  4.     String name;
  5.     //constructor to initialize integer and string
  6.     Student6(int i,String n){
  7.     id = i;
  8.     name = n;
  9.     }
  10.     //constructor to initialize another object
  11.     Student6(Student6 s){
  12.     id = s.id;
  13.     name =s.name;
  14.     }
  15.     void display(){System.out.println(id+” “+name);}
  16.     public static void main(String args[]){
  17.     Student6 s1 = new Student6(111,“Karan”);
  18.     Student6 s2 = new Student6(s1);
  19.     s1.display();
  20.     s2.display();
  21.    }
  22. }

Output:

111 Karan
111 Karan