Java Language Object Cloning Cloning performing a shallow copy

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


Default behavior when cloning an object is to perform a shallow copy of the object's fields. In that case, both the original object and the cloned object, hold references to the same objects.

This example shows that behavior.

import java.util.List;

public class Sheep implements Cloneable {

    private String name;

    private int weight;

    private List<Sheep> children;

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

    public Object clone() throws CloneNotSupportedException {
        return super.clone();

    public List<Sheep> getChildren() {
        return children;

    public void setChildren(List<Sheep> children) {
        this.children = children;


import java.util.Arrays;
import java.util.List;

// create a sheep
Sheep sheep = new Sheep("Dolly", 20);

// create children
Sheep child1 = new Sheep("Child1", 4);
Sheep child2 = new Sheep("Child2", 5);

sheep.setChildren(Arrays.asList(child1, child2));

// clone the sheep
Sheep dolly =  (Sheep) sheep.clone();
List<Sheep> sheepChildren = sheep.getChildren();
List<Sheep> dollysChildren = dolly.getChildren();
for (int i = 0; i < sheepChildren.size(); i++) {
    // prints true, both arrays contain the same objects
    System.out.println(sheepChildren.get(i) == dollysChildren.get(i));

Got any Java Language Question?