Copy Constructor in Java

Copy constructor in Java is a constructor that creates a new object by copying the values of the fields of an existing object of the same class. Copy constructors are not a standard feature in Java and are not part of the language specification, but they can be useful in certain situations.


Here's an example of a class with a copy constructor:

public class Car {
    private int speed;
    private String model;

    // constructor
    public Car(int speed, String model) {
        this.speed = speed;
        this.model = model;
    }

    // copy constructor
    public Car(Car car) {
        this.speed = car.speed;
        this.model = car.model;
    }
}


And here's an example of how you might use the copy constructor to create a new object:

Car originalCar = new Car(60, "sedan"); Car copyCar = new Car(originalCar);


In this example, the originalCar object is used to initialize a new copyCar object by calling the copy constructor. The values of the speed and model fields of originalCar are copied to the new object. This allows you to create a new object with the same values as an existing object, without having to manually set each field one by one.


It's worth noting that there are other ways to make a copy of an object in Java, such as using the clone() method or creating a new object with the same values using a constructor or setter methods. The choice of method depends on the specific requirements and design of your program.