There is no clone()
method in the Cloneable
interface. As @Ivan points out, if your class does not implement Cloneable
then calling Single#clone()
will throw a CloneNotSupportedException
.
That said, cloning is something that happens infrequently in well-written Java these days. As Josh Bloch writes in Effective Java, Item 11:
The Cloneable
interface was intended as a mixin interface (Item 18) for objects to
advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its
primary flaw is that it lacks a clone
method, and Object
's clone method is protected.
You cannot, without resorting to reflection (Item 53), invoke the clone
method on an object merely because it implements Cloneable
. Even a reflective
invocation may fail, as there is no guarantee that the object has an accessible
clone
method. Despite this flaw and others, the facility is in wide use so it pays to
understand it.
...basically, people don't/shouldn't use clone()
. It's a poorly designed interface, and if you want your objects to be cloneable, it's better to provide a copy constructor or copy factory method (code stolen from Item 11):
public Yum(Yum yum); // copy constructor
public static Yum newInstance(Yum yum); // copy factory
And while I'm talking about Effective Java, there's a better way to write a singleton, assuming that you really do need one (which is a big if!).
As of release 1.5, there is a third approach to implementing singletons. Simply
make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it
is more concise, provides the serialization machinery for free, and provides an
ironclad guarantee against multiple instantiation, even in the face of sophisticated
serialization or reflection attacks. While this approach has yet to be widely
adopted, a single-element enum type is the best way to implement a singleton.