Skip to lesson

Copy constructors and copy methods

A copy constructor builds a new object from another object of the same class: Student(Student other). The class copies itself, so callers never have to list its fields.

Copying belongs inside the class

A copy constructor is a constructor that takes one object of its own class as its parameter and builds a new object with the same field values, for example Student(Student other). Java does not write one for you.

In Assignment is not a copy (opens in a new tab), every caller listed the fields: new Receipt(t.college, t.student, t.amount). Add a field later and every such line must change. Only the class knows all its fields, so the class should copy itself.

Example 1 · The smallest copy constructor

CopyConstructorDemo.javaJava
class Student {    String name;    int roll;
    Student(String name, int roll) {        this.name = name;        this.roll = roll;    }
    Student(Student other) {        this.name = other.name;        this.roll = other.roll;    }}
public class CopyConstructorDemo {    public static void main(String[] args) {        Student original = new Student("Diya", 7);        Student copy = new Student(original);
        copy.name = "Diya S";
        System.out.println(original.name + ", roll " + original.roll);        System.out.println(copy.name + ", roll " + copy.roll);        System.out.println("same object? " + (original == copy));    }}
Output
Diya, roll 7
Diya S, roll 7
same object? false

What this code does

  • new Student(original) runs the copy constructor, which makes a new object and copies both fields from other.
  • The copy is a separate object, so renaming it leaves the original unchanged.

Example 2 · Group tickets from one booking

GroupTicketDemo.javaJava
class Ticket {    private String pnr;    private String train;    private String passenger;    private int seat;
    Ticket(String pnr, String train, String passenger, int seat) {        this.pnr = pnr;        this.train = train;        this.passenger = passenger;        this.seat = seat;    }
    Ticket(Ticket other) {        this.pnr = other.pnr;        this.train = other.train;        this.passenger = other.passenger;        this.seat = other.seat;    }
    void setPassenger(String passenger) {        this.passenger = passenger;    }
    void setSeat(int seat) {        this.seat = seat;    }
    @Override    public String toString() {        return "PNR " + pnr + " | " + train + " | " + passenger + " | seat " + seat;    }}
public class GroupTicketDemo {    public static void main(String[] args) {        Ticket first = new Ticket("4521836790", "12627 Karnataka Exp", "Aarav", 32);
        Ticket second = new Ticket(first);        second.setPassenger("Priya");        second.setSeat(33);
        Ticket third = new Ticket(first);        third.setPassenger("Rohan");        third.setSeat(34);
        System.out.println(first);        System.out.println(second);        System.out.println(third);    }}
Output
PNR 4521836790 | 12627 Karnataka Exp | Aarav | seat 32
PNR 4521836790 | 12627 Karnataka Exp | Priya | seat 33
PNR 4521836790 | 12627 Karnataka Exp | Rohan | seat 34

What this code does

  • Every field is private, yet the copy constructor reads other.pnr and the rest, because it is code inside Ticket.
  • Each new Ticket(first) starts from the same booking details; changing a copy's passenger and seat never touches Aarav's ticket.

Without a copy constructor, new Student(original) does not compile: Java adds no copy constructor of its own. Inside the class, other.pnr is allowed even when pnr is private, because access is checked per class, not per object.

Array fields need their own copy

A defensive copy is a fresh copy of a changeable object, such as an array, that a class makes when it receives one or hands one out. Outside code then cannot change the class's private data through a reference it still holds.

Kavya asks for re-evaluation, and the office edits a copy of her marksheet. A copy constructor with this.marks = other.marks; copies only the array's reference.

Example 3 · Mistake: the copy shares the marks array

RevaluationBugDemo.javaJava
import java.util.Arrays;
class Marksheet {    String name;    int[] marks;
    Marksheet(String name, int[] marks) {        this.name = name;        this.marks = marks;    }
    Marksheet(Marksheet other) {        this.name = other.name;        this.marks = other.marks;    }
    void setMark(int subject, int newMark) {        marks[subject] = newMark;    }
    @Override    public String toString() {        return name + " " + Arrays.toString(marks);    }}
public class RevaluationBugDemo {    public static void main(String[] args) {        Marksheet original = new Marksheet("Kavya", new int[] {78, 64, 91});        Marksheet revalued = new Marksheet(original);
        revalued.setMark(1, 72);
        System.out.println("Original: " + original);        System.out.println("Revalued: " + revalued);    }}
Output
Original: Kavya [78, 72, 91]
Revalued: Kavya [78, 72, 91]

What this code does

  • Kavya applied for re-evaluation of subject 1. The office edited a copy, but the original marksheet changed too.
  • this.marks = other.marks; copied only the reference, so both marksheets share one array. Changing name this way would be safe; changing the array is not.

Example 4 · Fix: copy the array too

RevaluationFixDemo.javaJava
import java.util.Arrays;
class Marksheet {    String name;    int[] marks;
    Marksheet(String name, int[] marks) {        this.name = name;        this.marks = Arrays.copyOf(marks, marks.length);    }
    Marksheet(Marksheet other) {        this.name = other.name;        this.marks = other.marks.clone();    }
    void setMark(int subject, int newMark) {        marks[subject] = newMark;    }
    @Override    public String toString() {        return name + " " + Arrays.toString(marks);    }}
public class RevaluationFixDemo {    public static void main(String[] args) {        Marksheet original = new Marksheet("Kavya", new int[] {78, 64, 91});        Marksheet revalued = new Marksheet(original);
        revalued.setMark(1, 72);
        System.out.println("Original: " + original);        System.out.println("Revalued: " + revalued);        System.out.println("Same array? " + (original.marks == revalued.marks));    }}
Output
Original: Kavya [78, 64, 91]
Revalued: Kavya [78, 72, 91]
Same array? false

What this code does

  • other.marks.clone() gives the copy its own array, so the re-evaluated mark changes only the copy.
  • The main constructor also copies the array it receives, so no outside code can share it either.

This is the defensive copy from Read-only objects (opens in a new tab), now inside a copy constructor. Primitive and String fields can be copied with plain =: a primitive is copied by value, and a String can never change.

Predict the output

Whose books changed?

Read the code and pick what it prints.

Round 1 of 2

The copy constructor copies the books array with =. What prints?

class Bag {
String owner;
String[] books;
Bag(String owner, String[] books) {
this.owner = owner;
this.books = books;
}
Bag(Bag other) {
this.owner = other.owner;
this.books = other.books;
}
}
public class Main {
public static void main(String[] args) {
Bag aarav = new Bag("Aarav", new String[] {"Physics", "Maths"});
Bag kiran = new Bag(aarav);
kiran.owner = "Kiran";
kiran.books[1] = "Chemistry";
System.out.println(aarav.owner + " " + aarav.books[1]);
}
}

Copy methods: copyOf and copy()

A copy factory method is a static method, such as Student.copyOf(s), that returns a new copy of the object it receives. A copy method, such as s.copy(), is an instance method that returns a copy of its own object.

Callers like names that say what they do, as in Arrays.copyOf. A method can also accept null safely, which new Student(null) cannot.

Example 5 · A static copyOf and a copy() method

CopyMethodsDemo.javaJava
class Student {    private String name;    private int roll;
    Student(String name, int roll) {        this.name = name;        this.roll = roll;    }
    Student(Student other) {        this.name = other.name;        this.roll = other.roll;    }
    static Student copyOf(Student s) {        if (s == null) {            return null;        }        return new Student(s);    }
    Student copy() {        return new Student(this);    }
    void setName(String name) {        this.name = name;    }
    @Override    public String toString() {        return name + " (roll " + roll + ")";    }}
public class CopyMethodsDemo {    public static void main(String[] args) {        Student monitor = new Student("Arjun", 12);        Student assistant = null;
        Student monitorCopy = Student.copyOf(monitor);        Student assistantCopy = Student.copyOf(assistant);        Student spare = monitor.copy();
        monitorCopy.setName("Arjun R");
        System.out.println(monitor);        System.out.println(monitorCopy);        System.out.println(spare);        System.out.println(assistantCopy);    }}
Output
Arjun (roll 12)
Arjun R (roll 12)
Arjun (roll 12)
null

What this code does

  • Student.copyOf(monitor) and monitor.copy() both end in new Student(...), so the real copying lives only in the copy constructor.
  • The class has no assistant yet. copyOf(null) returns null, while new Student(assistant) would crash with a NullPointerException on other.name.
  • copy() passes this, the object it was called on, to the copy constructor.

Keep the real work in the copy constructor and let both methods call it, so the list of fields exists in one place. Add the methods only when callers find them handy.

Chaining: this(...) and super(other)

A copy constructor can hand the other object's values to the main constructor with this(...), as in Constructor chaining (opens in a new tab). In a child class, super(other) lets the parent copy its own part first.

Example 6 · A child copy with super(other) and this(...)

TopperCopyDemo.javaJava
import java.util.Arrays;
class Student {    private String name;    private int[] marks;
    Student(String name, int[] marks) {        for (int m : marks) {            if (m < 0 || m > 100) {                throw new IllegalArgumentException("Bad mark: " + m);            }        }        this.name = name;        this.marks = Arrays.copyOf(marks, marks.length);    }
    Student(Student other) {        this(other.name, other.marks);    }
    void setMark(int subject, int mark) {        marks[subject] = mark;    }
    @Override    public String toString() {        return name + " " + Arrays.toString(marks);    }}
class Topper extends Student {    private int rank;
    Topper(String name, int[] marks, int rank) {        super(name, marks);        this.rank = rank;    }
    Topper(Topper other) {        super(other);        this.rank = other.rank;    }
    void setRank(int rank) {        this.rank = rank;    }
    @Override    public String toString() {        return super.toString() + " rank " + rank;    }}
public class TopperCopyDemo {    public static void main(String[] args) {        Topper diya = new Topper("Diya", new int[] {98, 95}, 1);        Topper draft = new Topper(diya);
        draft.setMark(1, 99);        draft.setRank(2);
        System.out.println("Real:  " + diya);        System.out.println("Draft: " + draft);    }}
Output
Real:  Diya [98, 95] rank 1
Draft: Diya [98, 99] rank 2

What this code does

  • Topper(Topper other) starts with super(other), so Student's copy constructor copies the name and marks; then the child copies rank.
  • Student(Student other) is one line, this(other.name, other.marks), so the copy passes the mark check and gets its own marks array from Arrays.copyOf.
  • Changing the draft's mark and rank leaves Diya's real record untouched.

this(other.name, other.marks) sends every copy through the main constructor, so its checks and its array copy run for copies too. If someone later adds a parameter to the main constructor, this line stops compiling: a forgotten field becomes a compile error instead of a silent bug.

super(other) works because a Topper can be passed where a Student is expected, as in The super keyword (opens in a new tab). The parent copies its fields; the child copies only rank.

Order of execution

Order of a child copy

Tap the steps of new Topper(original) in the order they run.

class Student {
String name;
int[] marks;
Student(String name, int[] marks) {
this.name = name;
this.marks = marks.clone();
}
Student(Student other) {
this(other.name, other.marks);
}
}
class Topper extends Student {
int rank;
Topper(Topper other) {
super(other);
this.rank = other.rank;
}
}

Next step

Check your understanding

12 quick questions