In this lesson, you will learn
public class MyClass {
// ... fields ...
// Copy constructor
public MyClass(MyClass originalObject) {
// Copy values from originalObject to the new object's fields
this.field1 = originalObject.field1;
this.field2 = originalObject.field2;
// ... copy other fields ...
}
}
Book originalBook=new Book(1984, "George Orwell");
Book copiedBook=new Book(originalBook);
Create an object ‘originalBook’ that duplicates the existing object ‘copiedBook’ passes to it. Let’s understand the workings of a copy constructor.

package ch7.l8;
class Book {
int year;
String author;
// Regular constructor
public Book(int y, String a) {
year = y;
author = a;
}
// Copy constructor
public Book(Book another) {
year = another.year;
author = another.author;
}
}
public class BookCopyMain {
public static void main(String[] args) {
Book originalBook = new Book(1984, "George Orwell");
Book copiedBook = new Book(originalBook);
System.out.println("Original Book: "+originalBook.year
+ ", " + originalBook.author);
System.out.println("Copied Book: "+copiedBook.year
+ ", " + copiedBook.author);
}
}
Output
Original Book: 1984, George Orwell
Copied Book: 1984, George Orwell
It’s used to create a new object as a copy of an existing object.

//Creates a new object
Book originalBook= new Book(1984, "George Orwell");
Book refBook= originalBook;
//refBook now refers to the same object as originalBook

Use a copy constructor when you need a new object with the same state as an existing object but want to keep the objects independent. Use the assignment operator when you simply need another reference to the same object.
Here’s a breakdown of the difference between a copy constructor and simply assigning object references:
Think of it like this:
package ch7.l8;
class RectangleCopy {
double length, width;
public RectangleCopy(double l, double w) {
length = l;
width = w;
}
// Copy constructor
public RectangleCopy(RectangleCopy anotherRectangle) {
length = anotherRectangle.length;
width = anotherRectangle.width;
}
}
public class RectangleCopyMain {
public static void main(String[] args) {
RectangleCopy originalRectangle = new RectangleCopy(5.0, 2.0);
RectangleCopy copiedRectangle = new RectangleCopy(originalRectangle);
System.out.println("Original Rectangle: "+copiedRectangle.length
+", "+copiedRectangle.width);
System.out.println("Copied Rectangle: "+copiedRectangle.length
+", "+copiedRectangle.width);
}
}
Output
Original Rectangle: 5.0, 2.0
Copied Rectangle: 5.0, 2.0
Very helpful to understand the concept of copy constructor .
Easy to understand.
Explain the topic with the help of examples.
You must be logged in to submit a review.