Tutorial by Examples

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) { this.name = name; this.weight = weight; } // copy constructor // copies...
Cloning an object by implementing the Cloneable interface. public class Sheep implements Cloneable { private String name; private int weight; public Sheep(String name, int weight) { this.name = name; this.weight = weight; } @Override public Ob...
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 { ...
To copy nested objects, a deep copy must be performed, as shown in this example. import java.util.ArrayList; import java.util.List; public class Sheep implements Cloneable { private String name; private int weight; private List<Sheep> children; public Sheep(Str...
public class Sheep { private String name; private int weight; public Sheep(String name, int weight) { this.name = name; this.weight = weight; } public static Sheep newInstance(Sheep other); return new Sheep(other.name, other.wei...

Page 1 of 1