on Leave a Comment

Java Copy Constructor

copy constructor copies all the data members of an existing object to the new object of same class. In java, if we don't define any copy constructor, then compiler doesn't create default copy constructor. Copy constructor is similar to parameterized constructor except that we have to pass the reference of an object as the parameter. 

Example of Java Copy Constructor

class CopyConstructor
{
 int id;
 String name;
 CopyConstructor(int i, String n)
 {
  id = i;
  name = n;
 }
 void showData()
 {
  System.out.println("\nDetails:\nId : "+id+"\nName : "+name);
 }
 CopyConstructor(CopyConstructor c)
 {
  id = c.id;
  name = c.name;
 }
 public static void main(String[] args) {
  CopyConstructor c1 = new CopyConstructor(1, "Albert");
  c1.showData();
  CopyConstructor c2 = new CopyConstructor(c1);
  System.out.println("\nAfter Copy Constructor Execution, new object fields are:");
  c2.showData();
 }
}


Output:

Details:
Id : 1
Name : Albert

After Copy Constructor Execution, new object fields are:

Details:
Id : 1
Name : Albert

0 comments:

Post a Comment