Java Copy Constructor
- Introduction:
Copy constructor in Java class is a constructor that creates an object using another object of the same Java class.
Read more …………… 127.0.0.1:62893 Meaning, Error And Fixing Tips
This happens when we need to copy a complex object that has a lot of fields, or when we want to make a deep copy of an existing object. Java Copy Constructor
Read More …… Conda Remove Environment – How to Delete an Env
- How to Create a Copy Constructor
To create a copy constructor, we first need to specify a constructor that takes an object of the same type as a parameter:
public class Employee { private int id; private String name; public Employee(Employee employee) { } } |
Then, we copy each field of the input object into the new instance:
public class Employee { private int id; private String name; public Employee(Employee employee) { this.id = employee.id; this.name = employee.name; } } |
What we have here is a shallow copy, which is fine because all of our fields – in this case an int and a string – are either primitive types or immutable types.
If a Java class has mutable fields, we can make a deep copy inside its copy constructor. With a deep copy, the newly created object is completely independent of the original object because we create a separate copy of each mutable object:
public class Employee { private int id; private String name; private Date startDate; public Employee(Employee employee) { this.id = employee.id; this.name = employee.name; this.startDate = new Date(employee.startDate.getTime()); } } |
- Copy Constructor vs. Clone
- In Java, we also use clone method to create an object from an existing object. However, copy constructor has many advantages over clone method:
- Copy constructor is very easy to implement. We do not need to implement Cloneable interface and handle CloneNotSupportedException. Java Copy Constructor
- Clone method returns a normal object reference. So, we need to typecast it appropriately.
- We cannot assign any value to final field in clone method. However, we can do so in copy constructor. Java Copy Constructor
- Inheritance Issues
Copy constructors in Java cannot be inherited by subclasses. So, if we try to initialize a child object from a parent class reference, we will face casting problem while cloning with copy constructor.
To illustrate this issue, let’s first create a subclass of Employee and its copy constructor:
public class Manager extends Employee { private List directReports; // … other constructors public Manager(Manager manager) { super(manager.id, manager.name, manager.startDate); this.directReports = manager.directReports.stream() .collect(Collectors.toList()); } } |
Then, we declare an Employee variable and instantiate it with the Manager constructor:
Employee source = new Manager(1, “Baeldung Manager”, startDate, directReports); |
Since the reference type is Employee, we have to cast it to Manager type so that we can use the copy constructor of the Manager class:
Employee clone = new Manager((Manager) source); |
We may get ClassCastException at runtime if the input object is not an instance of Manager class.
One way to avoid casting in the copy constructor is to create a new inheritable method for both classes:
public class Employee { public Employee copy() { return new Employee(this); } } public class Manager extends Employee { @Override public Employee copy() { return new Manager(this); } } |
In each class method, we call its copy constructor with the input of this object. In this way, we can guarantee that the generated object equals the caller object:
Employee clone = source.copy(); |
Example
// Java Program to Illustrate Copy Constructor
// Class 1
class Complex {
// Class data members
private double re, im;
// Constructor
public Complex(double re, double im)
{
// this keyword refers to current instance itself
this.re = re;
this.im = im;
}
}
// Class 2
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of above class
// inside main() method
Complex c1 = new Complex(10, 15);
// Note: compiler error here
Complex c2 = new Complex(c1);
}
}
- Conclusion
In this tutorial, we have explained how to create a copy constructor with some code examples. Also, we discussed many reasons why we should stay away from the clone method.
Casting problem in copy constructor occurs when we use it to clone a child class object whose reference type is the parent class. We have provided a solution for this problem.
As always, the source code of the tutorial is available on GitHub.