Search code examples
javagenericsinterfaceclonecloneable

Java public clone interface


Is there anything bad or wrong about creating an interface like this and use it in a place i need to make sure a variable is cloneable?

public interface PublicCloneable<I> {
    public I clone();
}

The are questions in SO related on the fact that the Cloneable interface of java is broken and i don't understand why it isn't implemented like this.


Solution

  • You can. The main problem with creating a new interface is that you can only use this interface on new classes that you create, which explicitly implement this interface. Existing classes in the Java library cannot implement this interface, since you can't change their code. (The interface does not magically apply to existing types.) So it's only useful if you kind of create of create a family of custom classes for all the objects you expect to use, and don't use the standard library classes.