Is it a good practice to override clone
method, without implementing Cloneable interface and not calling super.clone(). This way, CloneNotSupportedException
exception will not be thrown.
Consider this class :
class Money {
private BigDecimal x ;
public Object clone() {
Money m1 = new Money();
m1.setX(this.x);
return m1;
}
public BigDecimal getX() {
return x;
}
public void setX(BigDecimal x) {
this.x = x;
}
}
This class, does not throw CloneNotSupportedException
and it works just like a copy constructor.
Is this a good way to do it ?
You have your cloning logic and of course you know, that your class supports cloning and therefore clone
method should not throw CloneNotSupportedException
. So calling super.clone()
here causes you to write boilerplate try
/catch
block with rethrowing CloneNotSupportedException
wrapped inside AssertionError
, which is obviously never thrown. And this marker Cloneable
... I think, that this part of Java is misdesigned. So I just ignore documentation and copy fields by hands.
The only two arguments for using super.clone()
are performance (I suppose, something like memcpy
used internally) and persistence to errors when new fields added.
It's bad practice not to call super.clone()
. See this answer for more on how to implement the clone method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With