top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Copy Constructor in Java

Overview

Do you want to be proficient in Java? Read this tutorial to master copy constructor, a vital concept in Java. This tutorial covers the advantages of copy constructors, copy constructor vs. clone() method, writing a copy constructor, and creating duplicate objects without a copy constructor.

What Are Copy Constructors?

Copy constructors in Java are special constructors. They allow the creation of a new object by copying the values of an already present object of the same class. You can create an exact duplicate of an object by deploying copy constructors.

Writing a Copy Constructor

The copy constructor has the same name as the class. For instance, if the class name is upGrad, the copy constructor will also be named upGrad. The copy constructor does not have a return type, not even void. It is responsible for creating a new object, so it doesn't return anything explicitly.

For example, for the class upGrad:

public class upGrad {
    public upGrad(upGrad object) {
        // Copy the values from the provided object to create a new object
        // Assign the field values of 'object' to the corresponding fields of 'this' object
    }


    // Other constructors and methods of the class
}

The copy constructor takes a single parameter of the same class type as the one being constructed. This parameter represents the object from which the values are to be copied. In the example syntax, the parameter is named object and has the type upGrad.

The access specifier of the copy constructor is typically set to the same as the class's other constructors and methods. It determines the visibility and accessibility of the constructor from other parts of the code. In the above example, the copy constructor is declared with the default access specifier (public), which means it is accessible within the same package.

In the example above, upGrad is a class with two fields: field1 of type int and field2 of type String. The copy constructor takes an object of the same class (upGrad) as a parameter named object.

Inside the copy constructor, the values of field1 and field2 are copied from the provided object to the new object created using the this reference. This way, when you create a new instance of upGrad using the copy constructor, the values of field1 and field2 will be identical to those of the object you passed as an argument.

Now that you know how to use a copy constructor let us look at a working program:

public class upGradTutorials {
    private int value;
    // Constructor
    public upGradTutorials(int value) {
        this.value = value;
    }
    // Copy constructor
    public upGradTutorials(upGradTutorials other) {
        this.value = other.value;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public static void main(String[] args) {
        upGradTutorials obj1 = new upGradTutorials(10);
        upGradTutorials obj2 = new upGradTutorials(obj1); // Using the copy constructor
        System.out.println(obj1.getValue()); // Output: 10
        System.out.println(obj2.getValue()); // Output: 10

        obj1.setValue(20);

        System.out.println(obj1.getValue()); // Output: 20
        System.out.println(obj2.getValue()); // Output: 10
    }
}

In the above example, we create two instances of the upGradTutorials class: obj1 and obj2 in the main method. obj1 is initialized with a value of 10 using the constructor, and obj2 is created using the copy constructor, passing obj1 as an argument.

We then print the values of obj1 and obj2, which initially show 10 for both. After that, we change the value of obj1 to 20 using the setValue method. When we print the values again, we can see that the change in obj1 does not affect obj2, demonstrating the behavior of a copy constructor.

Advantages of Copy Constructor in Java

Using a copy constructor in Java offers several advantages that can greatly benefit programmers in code implementation.

First, a copy constructor reduces complexities when dealing with objects that have multiple parameters. The copy constructor provides a concise and convenient way to create a new object. This is done instead of passing each parameter individually. It is done by merely providing an existing object as the parameter. As a result, this simplifies the code.

Second, a copy constructor simplifies updating the constructor when a new field is added to the class. Only the input parameter must be updated in the constructor to include the new field, rather than modifying every instance where the constructor is called throughout the codebase. This reduces the chances of introducing errors. It also saves time during maintenance.

Also, using a copy constructor makes the need for typecasting redundant. The copy constructor creates a new object of a similar class. Hence, there is no requirement to cast the object explicitly. This enhances code clarity. It also minimizes the risk of type-related errors.

Finally, a copy constructor allows modification of fields declared as final. As we know, regular constructors cannot modify final fields once they are initialized. However, a copy constructor can overwrite these fields during object creation. This can be useful when creating a new object with similar values but with some alterations.

Creating Duplicate Objects Without Using a Copy Constructor

We can create duplicate objects in Java without using a copy constructor by utilizing other techniques, such as implementing the Cloneable interface and overriding the clone() method.

Here is an example:

In the above program, the upGradTutorials class implements the Cloneable interface, indicating that class instances can be cloned. The class also overrides the clone() method inherited from Object to enable cloning.

Inside the main method, we create an instance of upGradTutorials named obj1 with an initial value of 10. We then attempt to clone obj1 using the clone() method and assign the cloned object to obj2.

We print the values of obj1 and obj2, which initially show 10 for both. After that, we modify the value of obj1 to 20 using the setValue method. When we print the values again, we will observe that the change in obj1 does not affect obj2 (similar to the operation of a copy constructor), indicating that the cloning operation created a separate object.

Default Copy Constructor in Java

In Java, there is no default copy constructor provided by the language itself. However, the compiler automatically generates a default copy constructor if we do not define any constructor in your class. This default copy constructor performs a shallow copy of the object's fields, meaning it copies the field references rather than creating new objects.

Here is an example:

public class upGradTutorials {
    private int value;
    private String name;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public static void main(String[] args) {
        upGradTutorials obj1 = new upGradTutorials();
        obj1.setValue(10);
        obj1.setName("Aritra");

        upGradTutorials obj2 = new upGradTutorials();
        obj2 = obj1; // Performing a shallow copy

        System.out.println(obj1.getValue()); // Output: 10
        System.out.println(obj1.getName()); // Output: Aritra

        System.out.println(obj2.getValue()); // Output: 10
        System.out.println(obj2.getName()); // Output: Aritra

        obj1.setValue(20);
        obj1.setName("Manisha");

        System.out.println(obj1.getValue()); // Output: 20
        System.out.println(obj1.getName()); // Output: Manisha


        System.out.println(obj2.getValue()); // Output: 20 (same as obj1)
        System.out.println(obj2.getName()); // Output: Manisha (same as obj1)
    }
}

Deep Copy Constructor Java

To create a deep copy constructor in Java, you need to manually copy each field of the object, ensuring that new instances of any mutable objects are created.

Here is an example:

public class Person {
    private String name;


    public Person(String name) {
        this.name = name;
    }

    public Person(Person other) {
        this.name = other.name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Person person1 = new Person("Atriya");
        Person person2 = new Person(person1); // Using the deep copy constructor

        System.out.println(person1.getName()); // Output: Atriya
        System.out.println(person2.getName()); // Output: Atriya

        person1.setName("Aritra");

        System.out.println(person1.getName()); // Output: Aritra
        System.out.println(person2.getName()); // Output: Atriya (unchanged)
    }
}

In this example, we have a Person class with a single name field. The class has a deep copy constructor that copies the value of the name field.

Inside the main method, we create a Person object person1 with an initial name. Then, we create another Person object, person2, by using the deep copy constructor, ensuring a new instance is created with the same name value.

We print the values of person1 and person2, which initially show the same name value.

Copy Constructor vs. Clone() Method

Feature

Copy Constructor

clone() Method

Definition

A special constructor that creates a new object. This is done by copying values from an existing object of the same class.

It is a method defined in the Cloneable interface. It creates a new object by copying the fields of an existing object.

Availability

Depends on whether the programmer defines and implements it.

Available for classes that implement the Cloneable interface.

Accessibility 

Can be accessed from any class within the same package or subclass.

Needs to be called using the clone() method and may require casting.

Object Creation

Creates a new object of the same class with copied values.

Creates a new object by copying fields, typically using a shallow copy.

Required Interface

No specific interface is required.

The class must implement the Cloneable interface.

Field Accessibility

Can access all fields, including private fields.

Can only access public and protected fields, requiring additional steps for private fields.

Copying Behavior 

Provides control over how fields are copied, allowing customization during object creation.

Copies fields using a shallow copy by default, requiring additional steps for deep copy.

Exceptions

Can throw exceptions as per the defined logic.

Requires handling of checked exceptions (CloneNotSupportedException).

Usage Flexibility

Offers flexibility in terms of customization and handling complex copying scenarios.

Provides less flexibility compared to copy constructors.

Inheritance and Polymorphism

Copy constructors are not inherited. They need to be explicitly defined in each subclass.

clone() method is inherited. They can be overridden in subclasses for customized behavior.

It is to be that copy constructor provides more flexibility and control over the object creation process. However, the clone() method provides a standardized approach for creating copies of objects.

Using a copy constructor is often a simpler and more readable approach. This is especially if you have control over the class and its implementation. Conversely, using the clone() method can be a suitable choice if you work with classes that already implement Cloneable and need to adhere to existing cloning conventions.

Conclusion

A copy constructor is essential in several circumstances where you would want to create a new object that is a copy of an existing object. If you wish to master concepts such as copy constructors in Java, seeking professional training is recommended. A certified course in Java can have several career benefits. Learning platforms such as upGrad have several courses in computer science that can help you master programming languages faster and establish a bright career as a professional. 

FAQs

1. Is a copy constructor the same as a regular constructor?

A copy constructor creates a new object by copying the values of an already present object. A regular constructor initializes a new object with initial values. Copy constructors are typically used for object duplication or cloning. Regular constructors are used for general object creation.

2. Can I create a deep copy using a copy constructor in Java?

By default, copy constructors in Java create a shallow copy. This means that the references to other objects are copied. But the objects themselves are not copied. To create a deep copy, you must explicitly handle the deep copying logic within the copy constructor.

3. Can a copy constructor be inherited by subclasses?

Subclasses do not inherit copy constructors. Still, a subclass can have a copy constructor. For this, it must define its own copy constructor explicitly. Each class in the inheritance hierarchy must implement its own copy constructor. This is the case if object copying behavior is required.

Leave a Reply

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