Java ProgramsOOPCopy Constructor

Copy Constructor in Java

intermediate·  OOP  ·  Constructors

Problem

A copy constructor takes another object of the same class and copies its field values into a brand-new object — Java doesn't provide one automatically the way some other languages do, so it has to be written by hand.

Create a Car class with a constructor that builds a new Car from an existing one's field values, independent of the original.

Input
new Car(original), then modify the copy's year
Output
Tesla Model 3 (2022) Tesla Model 3 (2023)

Java Program

Java
class Car { String model; int year; Car(String model, int year) { this.model = model; this.year = year; } // Copy constructor: builds a new object from an existing one's field values Car(Car other) { this.model = other.model; this.year = other.year; } void display() { System.out.println(model + " (" + year + ")"); } } public class CopyConstructorDemo { public static void main(String[] args) { Car original = new Car("Tesla Model 3", 2022); Car copy = new Car(original); copy.year = 2023; // changing the copy doesn't touch the original original.display(); copy.display(); } }

Output

Tesla Model 3 (2022) Tesla Model 3 (2023)

Core Logic

Reading another object's fields into a fresh object's fields, instead of sharing a reference to the original, produces a genuinely separate copy.

How It Works
  1. 1Car(Car other) takes an existing Car object instead of raw values.
  2. 2this.model = other.model; and this.year = other.year; copy each field's current value into the new object.
  3. 3new Car(original) builds copy as a distinct object holding the same values original had at that moment.
  4. 4Changing copy.year afterward only affects copy's own field — it doesn't reach back and change original.year, since they're two separate objects.
After copy.year = 2023;, original still prints "Tesla Model 3 (2022)" while copy prints "Tesla Model 3 (2023)", confirming they're independent.
💡

Key Point: Because String and int fields are copied by value here, the two objects share no state at all after construction — mutating one can never leak into the other.

Key Concepts

copy constructorobject independencefield copying

Related Programs