DEV Community

Eric Ahnell
Eric Ahnell

Posted on

The Perils of Java's Object.clone() method

As a Java programmer, it is sometimes noticed early on that Object.clone() exists, so you start relying on it to copy objects. It isn't an ideal solution to this problem, though: it is fragile, relying on both overriding Object.clone() AND implementing Cloneable; it can fail in weird ways, usually in the form of CloneNotSupportedExceptions being thrown; and finally, it is very easy to implement incorrectly - to copy an object properly, you need to call clone() on the superclass and cast it first. If not, things will break.

In my own code, I am generally only trying to copy objects I control, which means I give my objects copy constructors for this purpose. Creating one is simple enough, is a lot safer than cloning, and can be illustrated with a small example:

public class MyObject {
    // Fields
    private int counter;
    private boolean counterUsed;
    private final String name;
    private String description;

    // Constructor
    public MyObject() {
        this.counter = 0;
        this.counterUsed = false;
        this.name = "No name";
        this.description = "Please describe me!";
    }

    // Copy constructor
    public MyObject(final MyObject other) {
        this.counter = other.counter;
        this.counterUsed = other.counterUsed;
        this.name = other.name;
        this.description = other.description;
    }
    // ... rest of class goes here ...
}
Enter fullscreen mode Exit fullscreen mode

If I need a copy of a MyObject instance, I can explicitly request one with the copy constructor, then change anything I need changed. Most importantly, copy constructors can't fail in the same ways cloning can, and the C++ way to make them happens to also be the recommended way in Java - if you're familiar with C++, this will not take long to learn!

Top comments (1)

Collapse
 
trishaganesh09 profile image
Trisha

This was really helpful! Thank you.