Why doesn't java.lang.Cloneable override the clone () method in java.lang.Object?

The Java specification for the java.lang.Cloneable interface defines itself as meaning that any object that extends it also implements the clone() method, which remains inactive in java.lang.Object . In particular, he says that:

The class implements the Cloneable interface to indicate to the java.lang.Object#clone() method that it is legal for this method to instantiate this class for the field.

For me, this means that we should assume that every class that extends Cloneable therefore also has a public Object clone() method in it. This makes it easy to assume that a valid method is:

 public static makeACloneFrom(Cloneable c) { return c.clone(); } 

however, this is not the case since the entire source code of Cloneable (sans javadoc) is just

 package java.lang; public interface Cloneable { } 

This means that Cloneable#clone() does not exist (and trying to compile the method described above results in a compile-time error saying something like " cannot find symbol: method clone() "). Should the Cloneable source code have any effect on the effect of public Cloneable clone(); ?

Why are we not allowed to assume that a class that implements Cloneable has a public Cloneable clone() method?

+6
source share
2 answers

Because it is a poorly designed interface.

From Effective Java (sorry, Google Books has no preview for 2nd edition):

Item 11: Reasonably Override clone

The Cloneable was intended as the mixin interface (Item 18) for objects that advertise that they allow cloning. Unfortunately, it cannot serve this purpose. Its main drawback is that it lacks clone , and the Object clone method is protected. You cannot resort to reflection (point 53) to call the clone method on an object only because it implements Cloneable . Even a reflexive call may fail because there is no guarantee that the object has an available clone method.

+5
source

Ugh. clone and Cloneable broken, badly designed and should not be used in new code. (See "Effective Java Element 11".)

The reason for this is that Cloneable is a confusing magic interface, so the simple act of implementing Cloneable modifies the behavior of Object.clone with reflection. Effective Java says:

... if the class implements the Cloneable method, Object s clone returns a field copy of the object; otherwise, it throws a CloneNotSupportedException exception. This is a very atypical use of interfaces, not emulation ...

+6
source

Source: https://habr.com/ru/post/912254/


All Articles