I was reading up on performing a deep-copy of an array correctly, however I was confused about how the #clone()
is implemented. It is a member of the java.lang.Object
class, and yet if you read the javadocs:
First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown.
So why define the clone
method there in the first place? Surely if a method can only be used when an interface is present, you'd put the method in the interface. The Cloneable
interface itself is empty; it is just a marker interface used by Java to ensure that using the clone
method is legal.
Doing it this way also removes the ability to make use of generics to ensure type safety:
class Foo implements Cloneable { // Valid.
@Override
public Object clone() throws CloneNotSupportedException {
// ...
}
}
class TypeSafeFoo implements Cloneable<TypeSafeFoo> { // Not valid.
@Override
public TypeSafeFoo clone() throws CloneNotSupportedException {
// ...
}
}
Why has Java done it this way? I'm sure they have legitimate reasons, but I can't seem to figure it out.