Many consider ``++clone++`` and ``++Cloneable++`` broken in Java, largely because the rules for overriding ``++clone++`` are tricky and difficult to get right, according to Joshua Bloch:

____
Object's clone method is very tricky. It's based on field copies, and it's "extra-linguistic." It creates an object without calling a constructor. There are no guarantees that it preserves the invariants established by the constructors. There have been lots of bugs over the years, both in and outside Sun, stemming from the fact that if you just call super.clone repeatedly up the chain until you have cloned an object, you have a shallow copy of the object.  The clone generally shares state with the object being cloned. If that state is mutable, you don't have two independent objects. If you modify one, the other changes as well. And all of a sudden, you get random behavior.
____


A copy constructor or copy factory should be used instead.


This rule raises an issue when ``++clone++`` is overridden, whether or not ``++Cloneable++`` is implemented.


== Noncompliant Code Example

----
public class MyClass {
  // ...

  public Object clone() { // Noncompliant
    //...
  }
}
----


== Compliant Solution

----
public class MyClass {
  // ...

  MyClass (MyClass source) {
    //...
  }
}
----


== See

* https://www.artima.com/intv/bloch13.html[Copy Constructor versus Cloning]

=== See Also

* S2157 - "Cloneables" should implement "clone"
* S1182 - Classes that override "clone" should be "Cloneable" and call "super.clone()"


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
