Don_Quijote Don_Quijote - 1 year ago 53
Java Question

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

I know that

is a protected method, but "protected" means that it is accessible for all subclasses of particular class.

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

And why can we call
only on classes that implement the
I can't understand how it connects to the fact that
is declared as protected.


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) { 
        /* copy or deep-copy the state */ 

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