Why wasn't the .clone()
method specified in the java.lang.Cloneable
interface ?
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 aCopyable
, becauseCloneable
has problems. Besides the fact that it's misspelled,Cloneable
doesn't contain theclone
method. That means you can't test if something is an instance ofCloneable
, cast it toCloneable
, and invokeclone
. You have to use reflection again, which is awful. That is only one problem, but one I'd certainly solve.
Cloneable
at all. Cloneable
is just to make Object.clone()
throw an exception or not. It has never been an interface for you to invoke clone
. Maybe it would be nice if Java had such an interface, but lack of one does not make another interface (Cloneable
) broken. –
Bramble See this bug in the Java bugs database:
https://bugs.java.com/bugdatabase/view_bug?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.
const
parameters, but copying every (mutable) object instance isn't a good solution. And yes, there are some things in which Java sucks, and this is one of them. Use Kotlin / data classes. –
Cubby In Java, there is this 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:
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();
}
Because the clone method is implemented in the Object class due to its "special" condition: the memory copy of objects of any kind.
© 2022 - 2024 — McMap. All rights reserved.