Member-only story
Effective Java! Override clone judiciously
Today we are talking about the Cloneable
interface and it related clone
function. Honestly I haven't interacted any with this method in the past and after learning about it I'm not sure I really want to, it seems quite error prone. So let's dive in and understand this method so that we can make intelligent decisions about whether to use this method or not.
So what is the Cloneable
interface. It is a mixin interface that signals to users of the class that a certain action can be performed on the class. The extremely weird thing about this particular mixin is that, rather than requiring the implementation of a particular function, it merely acts as a flag that allows the implementing class to call a method on the parent class. What this means is that a user of the class that implements Cloneable
can't necessarily always call the clone
method on that class without resorting to reflection and even then that might not work. All this being said, this is a part of the Object
class so it pays to understand it and know how to implement the method as well as what the alternatives are. This chapter of Effective Java goes through that.
So what is the contract of Cloneable
? As we learned above it doesn't include any methods but instead acts as a flag to the protected clone
method in the Object
class. If a class calls the clone
on Object
and that class implements Cloneable
, Object
's implementation of clone
will return a field-by-field copy of the object. If the class does not implement Cloneable
, a CloneNotSupportedException
…