Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Clone without calling the super.clone

Tags:

java

clone

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 ?

like image 926
Vinoth Kumar C M Avatar asked Dec 02 '13 09:12

Vinoth Kumar C M


2 Answers

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.

like image 190
Alexey Andreev Avatar answered Nov 10 '22 05:11

Alexey Andreev


It's bad practice not to call super.clone(). See this answer for more on how to implement the clone method.

like image 43
Rinke Avatar answered Nov 10 '22 07:11

Rinke