Home » Core Java » copy Constructor in Java

copy Constructor in Java

 
Copy Constructor is a C++ fundamentals,but in Java also we can implement this feature in  different ways.

1 : By using cloning .Please visit the link  shallow cloning  for  details.

2 : By  using Constructor with argument  as previously created object of the same class .

3 : By  assigning all the values of members of one object to another object .

The below example shows second and third way of creating copy constructor .

Program ::
 
 

Output ::

In the above example always a new object reference is created ,so it copy constructor is similar to default shallow cloning.

Uses of Copy Constructor : 

1 : Copy constructor is useful if we want to modify the second object(Here obj2 ) only and not the first object(obj1) .So we can get the modified and original value at the same time .

2 : It is simple to create copy constructor by passing first object(obj1) to the constructor of second(obj2).
 
 


Leave a comment

Your email address will not be published. Required fields are marked *

ten + 12 =