Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding clone with and without Cloneable

Tags:

java

object

clone

I've read the javadoc for both Object and Cloneable and am just not "getting" something. Can someone please explain to me the performance and/or functional differences to the two following examples:

public class Widget
{
    @Override
    public Widget clone()
    {
            // ... return a clone of this Widget
    }
}

..and:

public class Widget implements Cloneable
{
    @Override
    public Widget clone()
    {
            // ... return a clone of this Widget
    }
}

Since Cloneable does not have any methods tied to it, and only gives you access to Object's protected clone() method, does it ever make sense to even implement it in the first place, seeing that you're going to have to end up writing your own (safe) clone() code any way? Thanks in advance for any clarification/input.

like image 502
IAmYourFaja Avatar asked Oct 14 '11 18:10

IAmYourFaja


1 Answers

It's a contractual obligation.

Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

While there may be no methods to override, you are still implementing an interface you are part of. In doing this you take on all that comes with its subsequent contract. It forces you to knowingly implement the clone() method thus making the behavior explicit.

like image 152
Aaron McIver Avatar answered Oct 26 '22 22:10

Aaron McIver