What are Copy Constructors In Java? Explore Types,Examples & Use

What are Copy Constructors In Java? Explore Types,Examples & Use

18 Apr 2024
Beginner
624 Views
13 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Copy Constructor in Java: An Overview

If you've worked with C++, you must be aware of the copy constructor in C++. But, unlike C++, where it is already created by default, in Java, you need to create a copy constructor specifically, when you need it. Let's learn more about this. In this article from the Java tutorial, we will understand the copy constructor in detail. For more details, consider our Java Certification.

Constructors: A Brief Introduction

Firstly, what are constructors in Java and what are they used for?

In Java, constructors are unique methods intended to initialize objects. They share the same name as the class. Constructors are automatically invoked when objects of the class are created. Their functions are to assign initial values to object attributes and carry out mandatory setup tasks during object instantiation. They can be considered as the "blueprints" for constructing objects in Java.

Types of Constructors in Java

There are 3 types of constructors in Java, they are:

  1. Default Constructor: It is automatically created by Java if there is no constructor specifically defined in the class.
  2. Parameterized Constructor: It is created with one or two parameters. It helps you to initialize object attributes with specific values.
  3. Read More: Constructors in Java: Types of Constructors with Examples

  4. Copy Constructor: It makes a copy object of another existing object with the same state and values. We'll learn further about copy constructors in detail.

Read More - Advanced Java Interview Questions

Copy Constructor in Java

In Java, the copy constructor is exactly what the name suggests. It is used to create a copy object of another existing object within the same Java class. It takes the existing object as a parameter and creates a duplicate object that will have the same values as in that existing object, which it is a copy of. This can be helpful when you want to make changes to an object without affecting its initial state.

Copy Constructor in Java

How to use a Copy Constructor?

Now, let's learn how to use a copy constructor in your program in a few easy steps:

  1. Create a class- First of all, you need to create a class for the object that will be copied with the help of a copy constructor. For instance, we created a class named ‘car’ with the attributes of ‘brand’, ‘model’, and ‘year’.
  2. Read More: What is Class in Java? - Objects and Classes in Java {Explained}

  3. Define the copy constructor- Inside the newly made ‘car’ class, define the copy constructor that will have the same name and parameters as the class. In this example, it will be a ‘car’ object.
  4. Copy attributes- Write a code in the copy constructor to copy the values of the parameter object to the newly created object. You can assign the values of all those attributes from the parameter ‘car’ object to the corresponding attributes of the new ‘car’ object.
  5. Create a new object- Now, whenever you want to make a copy of the ‘car’ object, you can easily create a ‘car’ object with the copy constructor by passing it as an argument in the copy constructor.
  6. Use the copy- Once, you've created the copy object, you can use it just like the initial ‘car’ object as it will have the same attributes as the original.
  7. That's it! You have easily used the copy constructor in your program.

Example demonstrating Copy Constructor in Java Compiler


public class Car {
    private String brand;
    private String model;
    private int year;

    // Default constructor
    public Car() {
        this.brand = "Unknown";
        this.model = "Unknown";
        this.year = 0;
    }

    // Parameterized constructor
    public Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    // Copy constructor
    public Car(Car otherCar) {
        this.brand = otherCar.brand;
        this.model = otherCar.model;
        this.year = otherCar.year;
    }

    // Getters and setters
    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    // Main method for testing
    public static void main(String[] args) {
        Car originalCar = new Car("Toyota", "Corolla", 2022);
        Car copiedCar = new Car(originalCar); // Using the copy constructor

        // Display original car details
        System.out.println("Original Car:");
        System.out.println("Brand: " + originalCar.getBrand());
        System.out.println("Model: " + originalCar.getModel());
        System.out.println("Year: " + originalCar.getYear());

        // Display copied car details
        System.out.println("\nCopied Car:");
        System.out.println("Brand: " + copiedCar.getBrand());
        System.out.println("Model: " + copiedCar.getModel());
        System.out.println("Year: " + copiedCar.getYear());
    }
}

This program defines the ‘car’ class, characterized by attributes such as brand, model, and year. It features all the constructors: a default constructor, a parameterized constructor, and a copy constructor. In the main method, an initial ‘car’ object is created, and the copy constructor is used to create a copy of this object. The program will give the output with details of both the original and copied cars, which will demonstrate that the copy constructor worked correctly.

Output

Original Car:
Brand: Toyota
Model: Corolla
Year: 2022

Copied Car:
Brand: Toyota
Model: Corolla
Year: 2022

Read More - Java Developer Salary

Advantages of Copy Constructor

The copy constructor can be helpful in many ways such as:

  • It simplifies object duplication by providing a convenient way to create copies with the same state.
  • It ensures that copied objects are independent from the original.
  • It explicitly indicates the intention to create a copy of an object enhancing code readability.
  • It enables changes in the copied objects preserving the initial class.
  • Facilitates the creation of deep copies, preserving the state of complex objects and their internal references.

Disadvantages of Copy Constructor

  • Copying complex objects can double the complexities.
  • There are limited benefits to using immutable objects.
  • The copy constructor might result in shallow copies if not implemented carefully.

Difference between Copy Constructor and Clone() Method

We also have a clone() method in Java that is used to create copies as well but then what is the difference between the two? The answer lies in their usage and implementation.

The copy constructor is initiated specifically within the class to create a new object by copying the values of another existing object. Whereas, the clone() method is a built-in method provided by the ‘cloneable’ interface in Java. It copies the object but the way it is implemented will decide if it will perform a shallow copy or a deep copy. Moreover, the clone() method can only return ‘typecast’ objects while there are no such necessary conditions in the case of a copy constructor.

To understand it better, here’s a short example:


class MyClass implements Cloneable {
    private int value;


    // Copy Constructor
    public MyClass(MyClass other) {
        this.value = other.value;
    }


    // Constructor
    public MyClass(int value) {
        this.value = value;
    }


    // Getter and Setter for value
    public int getValue() {
        return value;
    }


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


    // Clone Method
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }


    public static void main(String[] args) {
        // Creating object using constructor
        MyClass obj1 = new MyClass(10);


        // Using copy constructor
        MyClass obj2 = new MyClass(obj1);


        // Using clone method
        MyClass obj3 = null;
        try {
            obj3 = (MyClass) obj1.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }


        // Modifying values in obj1, obj2, and obj3
        obj1.setValue(20);


        // Displaying values
        System.out.println("obj1 value: " + obj1.getValue());
        System.out.println("obj2 value: " + obj2.getValue());
        System.out.println("obj3 value: " + obj3.getValue());
    }
}

In this program:

  • MyClass has a copy constructor that takes an instance of MyClass and copies its value.
  • It also has a clone method provided by implementing the Cloneable interface. This method uses ‘super.clone()’ to perform a shallow copy of the object.

We create ‘obj1’ using the constructor, ‘obj2’ using the copy constructor, and ‘obj3’ using the clone method.

After modifying the value of ‘obj1’, we see that the value of ‘obj2’ remains unchanged, reflecting the independent copy made by the copy constructor. However, the value of ‘obj3’ reflects the change made to ‘obj1’, indicating a shallow copy done by the clone method.

This demonstrates the difference between a copy constructor, which creates a new independent copy of an object, and a clone method, which creates a shallow copy that shares references to the same objects as the original.

Output

obj1 value: 20
obj2 value: 10
obj3 value: 10 
Summary

In conclusion, copy constructors in Java offer a powerful mechanism for creating new objects by copying the state of existing ones. They are basically used for creating immutable objects, deep copying, cloning, and custom initialization. By understanding the concept and usage of copy constructors, you can write a cleaner, more efficient, more robust Java code.

FAQs

Q1. What is the need of a copy constructor?

Copy constructor provides a seamless duplication process by automatically copying data fields , and it maintains a clear separation between the original and the copy, so that changes made to one object do not affect the other.

Q2. What is the difference between copying and cloning in Java?

In Java, copying typically refers to duplicating an object's state, while cloning involves creating a new object with a separate memory allocation.

Q3. Why copy constructor is not used in Java?

Copy constructors are not used in Java because Java already has a default copy constructor that performs shallow copying.
Share Article
Live Training Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this