There are two issues: first, clone()
is a protected
method of Object
, so it can only be called from within the subclass unless you override it and make it public. Second, unless your class implements Cloneable
, calling clone()
will throw a CloneNotSupportedException
. The typical approach is:
class A implements Cloneable {
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Impossible exception!", e);
}
}
}
(You could eliminate the try/catch block and declare your clone()
method to throw CloneNotSupportedException
. The method would be simpler but all the calling code would have to deal with the exception.)
Since Java allows you to narrow the return type when overriding a method, you could redefine clone()
to return an A
, saving the calling code from having to cast:
class A implements Cloneable {
public A clone() {
try {
return (A) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Impossible exception!", e);
}
}
}