Copy Constructor in Java With Examples

Copy Constructor in java class is a special type of constructor that takes same class as argument. Copy constructor is used to provide a copy of the specified object.

Copy Constructor in Java

Copy constructor is an easy alternative to java cloning mechanism.

Copy constructor is helpful when we want to copy an object that is heavy to instantiate. While writing copy constructor it’s very important to perform deep copy so that both the objects are detached. However in some cases where you don’t mind the change in object data, then you can also go for shallow copy.

Let’s see how to properly write a copy constructor in java and perform deep copy of the object.

Note that I am using project lombok so that I don’t have to write boiler-plate code.

Here is a simple test class where we are using copy constructor.

Notice that I am changing some properties in one of the object, if our deep copy implementation is correctly done then it shouldn’t affect the other object. Let’s run the above program and check the output.

It’s clear from the output that our copy constructor implementation is correct, change in one of the object didn’t affected the other object and our deep copy implementation is correct.

By admin

Leave a Reply

%d bloggers like this: