Cloning using a copy constructor

suggest change

An easy way to clone an object is by implementing a copy constructor.

public class Sheep {

    private String name;

    private int weight;

    public Sheep(String name, int weight) { = name;
        this.weight = weight;

    // copy constructor
    // copies the fields of other into the new object
    public Sheep(Sheep other) { =;
        this.weight = other.weight;


// create a sheep
Sheep sheep = new Sheep("Dolly", 20);
// clone the sheep
Sheep dolly = new Sheep(sheep); // is "Dolly" and dolly.weight is 20

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents