Search code examples
javainterfaceoverridingclone

Mandatory cloneable interface in Java


I'm having a small problem in Java. I have an interface called Modifiable. Objects implementing this interface are Modifiable.

I also have a ModifyCommand class (with the Command pattern) that receive two Modifiable objects (to swap them in a list further on - that's not my question, I designed that solution already).

The ModifyCommand class starts by making clones of the Modifiable objects. Logically, I made my Modifiable interface extends Cloneable. The interface then defines a clone() method that its implementing classes must redefine.

Then, in ModifyCommand, I can do : firstModifiableObject.clone(). My logic is that classes implementing Modifiable will have to redefine the clone method from Object, as they will be Cloneable (that's what I want to do).

The thing is, when I define classes implements Modifiable and I want to override clone(), it won't let me, stating that the clone() method from the Object class hides the one from Modifiable.

What should I do? I'm under the impression that "I'm doing it wrong"...

Thanks,

Guillaume.

Edit : it think I will forget the clone() thing. I will either a) assume that the object passed to the Modifiable object (implementing the interface) is already cloned or b) make another method called, for example, copy(), that would basically do a deep-copy of the Modifiable object (or maybe the Generic solution will work...).


Solution

  • If you're using java 1.5 or higher, you can get the behavior you want and remove casting this way:

    public interface Modifiable<T extends Modifiable<T>> extends Cloneable {
        T clone();
    }
    
    public class Foo implements Modifiable<Foo> {
        public Foo clone() { //this is required
            return null; //todo: real work
        }
    }
    

    Since Foo extends Object, this still satisfies the original contract of the Object class. Code that doesn't refine the clone() method correctly will not compile, because of the additional constraints imposed by the Modifiable interface. As a bonus, calling code doesn't have to cast the result of the clone method.