What are Copy Constructors In Java? Explore Types, Examples & Use
A copy constructor is a constructor that creates a new object by copying the values of fields from an existing object of the same class. Unlike languages such as C++, Java does not provide a built-in copy constructor — you write one yourself.
Example
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
Student(Student other) {
this.name = other.name;
this.age = other.age;
}
}
Student s1 = new Student("Riya", 21);
Student s2 = new Student(s1); // copy of s1
Types of Copying
- Shallow Copy — copies primitive fields and reference values directly, so reference type fields still point to the same objects
- Deep Copy — creates new copies of any referenced objects as well, so the two objects are fully independent
Deep Copy Example
class Address {
String city;
Address(String city) { this.city = city; }
Address(Address other) { this.city = other.city; }
}
class Student {
String name;
Address address;
Student(Student other) {
this.name = other.name;
this.address = new Address(other.address); // deep copy
}
}
When to Use a Copy Constructor
- When you need an independent copy of an object without affecting the original
- When cloning objects that contain mutable fields, to avoid shared-state bugs
- As a cleaner alternative to Java's
Cloneableinterface andclone()method
A copy constructor gives you full control over how each field is copied, which is why many developers prefer it over overriding
clone().Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.