views:

1902

answers:

5

Why wasn't the .clone() method specified in the java.lang.Cloneable interface ?

+2  A: 

See this bug in the Java bugs database:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4098033

Essentially, this is a design flaw in earlier versions of Java that they are not intending to fix in the Cloneable interface as to do so would break compatibility with some existing code.

David M
+1  A: 

Because the clone method is implemented in the Object class due to its "special" condition: the memory copy of objects of any kind.

fbinder
+1  A: 

In Java, there is this weird concept of marker interfaces. The Cloneable interface has no methods or fields and serves only to identify the semantics of being cloneable.

from the dev-x website:

Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Some examples of marker interfaces in the Java API include:

- java,lang.Cloneable
- java,io.Serializable
- java.util.EventListener
Peter Perháč
I don't think it's a weird concept. Sometimes it's useful to be able to see if something can act as an alternate type. As others have said, Cloneable is broken though.
John Topley
They're supposed to act as mixins. Not my favourite mechanism in a strongly typed language such as java but it makes sense for Serializable, sorta.
wds
@Serializable would have made more sense. Or at least it would have done if annotations came a decade earlier.
Tom Hawtin - tackline
I like the last comment by tom :) There were quite a few features that should have been in a decade ago...
Peter Perháč
Annotations would now replace these marker interfaces.
_ande_turner_
+5  A: 

Basically, it's a broken interface. Ken Arnold and Bill Venners discussed it in Java Design Issues.

Arnold:

If I were to be God at this point, and many people are probably glad I am not, I would say deprecate Cloneable and have a Copyable, because Cloneable has problems. Besides the fact that it's misspelled, Cloneable doesn't contain the clone method. That means you can't test if something is an instance of Cloneable, cast it to Cloneable, and invoke clone. You have to use reflection again, which is awful. That is only one problem, but one I'd certainly solve.

Bill the Lizard
+2  A: 

On the project I work on, we've created an interface called PublicCloneable, it contains the clone method and specifies that it is public.

I find this one useful: the fact that there's a clone method, but you cannot access it doesn't help very much.

public interface PublicCloneable extends Cloneable {
    public Object clone();
}

Nicolas