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

℡╲_俬逩灬. 提交于 2019-12-20 10:04:14

问题


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.


回答1:


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); }
}



回答2:


Because that's the way they designed it. There's a statement somewhere in the Bug Parade that the original reasons for the design are 'lost in the mists of time', but I remember a discussion by Sun in the 1990s that said the design gave four possible behaviors.

Cannot remember the details :-| But you can work it out:

  1. Do nothing. Class cannot be cloned and clone() method is inaccessible except to derived classes.
  2. Implement Cloneable: Class can be cloned but clone() method is inaccessible except to derived classes.
  3. Implement Cloneable and provide your own clone() method: as (2) but the possibility exists to make clone() public and also now to return the correct type.
  4. Derived from a class that does (2) or (3), implement clone(), and throw NotCloneableException: you are back to 1.

Putting clone() into the interface would have lost some of that.




回答3:


The default implementation of Object.clone() is the only way (other than perhaps Reflection) via which a base-type method in an object can produce a new object of that object's same type. On the other hand, there are many classes for which it would be impossible for a derived class to implement a working clone method which would not violate the base-class invariants. It was desired that such derived classes not be allowed to call clone and receive an object that couldn't possibly be usable.

In retrospect, the proper thing to have done might have been to define a system CloneableObject which inherits from Object which includes a protected memberwiseclone method (that works like Object.clone() does now) and nothing else, and have all classes which are going to be cloneable inherit from that as their base type. That type could use then some special magic within its clone() method that was unavailable to other types. Instead, however, the system uses the existence of the Cloneable interface to decide whether objects should be allowed to use the base-level clone() method. Not a great design, but it is what it is. Hard to say whether that's better or worse than the .NET approach of allowing nearly all derived classes to call MemberwiseClone whether or not there would be any way a derived class could do so without yielding a broken object.




回答4:


Cloneable is an interface and in order to clone a reference to an abstract base class, either the base class must have a clone() method, or one of its parents must have a publicly accessible clone() method. Cloneable just acts as a marker interface.

Please refer to:

  • clone (Java method)
  • Why is the clone() method protected in java.lang.Object?



回答5:


http://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.

Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

Coming to your question even though Object has protected method clone Object does not implement Cloneable,But the object being called the clone() method must implement Cloneable interface.




回答6:


Cloneable is a marker interface. The clone() method isn't defined by the Cloneable interface.

The clone method in the Object class is protected to prevent a client class from calling it - Only subclasses can call or override clone, and doing so is a bad idea.



来源:https://stackoverflow.com/questions/18240037/why-object-clone-method-available-only-to-classes-that-implement-cloneable-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!