Why Object clone() method available only to classes that implement Cloneable interface?

Don_Quijote picture Don_Quijote · Aug 14, 2013 · Viewed 20.2k times · Source

I know that clone() is a protected method, but "protected" means that it is accessible for all subclasses of particular class.

Any Java class is a subclass of Object, so what is the reason for the protected method here?

And why can we call clone() only on classes that implement the Cloneable interface? I can't understand how it connects to the fact that clone() in Object is declared as protected.

Answer

Cephalopod picture Cephalopod · Aug 14, 2013

Object's clone() method is quite special, as it always returns an instance of the current class that has all fields copied (even final). I don't think its possible to reproduce this with plain Java code, not even with reflection.

Because of this, it must be made available to all classes, but since it should not be callable from the outside by default because you don't want everything to be cloneable, it must be protected.

As an additional check, clone checks that the class implements Cloneable, only to ensure you don't clone non-cloneables by accident.


All in all, cloning is somewhat broken because it doesn't work when you need to deep-copy final fields. I recommend you implement instance copying manually, following this pattern.

public class Base {

    /** one or more public constructors */
    public Base() { ... }

    /** copy-constructor */
    protected Base(Base src) { /* copy or deep-copy the state */ }

    public Base copy() { return new Base(this); }
}

public class Derived extends Base {

    /** one or more public constructors */
    public Derived() { ... }

    /** copy-constructor */
    protected Derived(Derived src) { 
        super(src);
        /* copy or deep-copy the state */ 
    }

    @Override
    public Derived copy() { return new Derived(this); }
}