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.
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.
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