Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Java code to demonstrate that clone() is shallow by default
import java.util.Arrays;
import java.util.List;
class ClassWithState implements Cloneable {
int x = 15;
Long y = Long.MAX_VALUE / 3;
String z = new String("new Z");
List<String> data = Arrays.asList("a", "b", "and", "c");
protected Object clone() throws CloneNotSupportedException {
return super.clone();
public class CloneIsShallow {
public static void main(String[] args) throws Exception {
ClassWithState orig = new ClassWithState();
ClassWithState copy = (ClassWithState) orig.clone();
if (orig.x != copy.x || orig.y != copy.y || orig.z != copy.z || != {
throw new AssertionError("ERROR");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment