In your case yes you can override clone()
:
public class A {
}
public class B extends A implements Cloneable {
@Override
public B clone() throws CloneNotSupportedException {
return (B) super.clone();
}
}
and still have an effective clone mechanism - you are therefore telling the truth when you state implements Cloneable
.
However, all that is needed to break that promise is to give A
a private
variable.
public class A {
private int a;
}
and now your promise is broken - unless A implements clone
, in which case you can use super.clone()
:
public class A {
private int a;
@Override
public A clone() throws CloneNotSupportedException {
A newA = (A) super.clone();
newA.a = a;
return newA;
}
}
public class B extends A implements Cloneable {
private int b;
@Override
public B clone() throws CloneNotSupportedException {
B newB = (B) super.clone();
newB.b = b;
return newB;
}
}
Essentially - as Joshua Bloch states - if you don't implement clone
your sub-classes also cannot (generally).