JohnJohnGa
JohnJohnGa

Reputation: 15685

Java interface extends Cloneable

I don't understand why we can't do the following:

interface MyInterface extends Cloneable {}

class myClazz implements MyInterface {
    public Object clone() { return null; }
}

class test{
    public static void main(String[]a){
        MyInterface o = new myClazz();
        o.clone(); // IMPOSSIBLE
    }
}

But this will work fine

interface Misc{
    public void testM();
}

interface MyInterface extends Misc{}

class myClazz implements MyInterface {
    public void testM() {}
}

class test{
    public static void main(String[]a){
        MyInterface o = new myClazz();
        o.testM(); // OK
    }
}

What's happen with Cloneable?

Thanks,

Upvotes: 3

Views: 6583

Answers (3)

Jack
Jack

Reputation: 133587

This beacause the Cloneable interface is not a normal interface but more or less a tagging interface which ensures to the JVM that the clone method of the class that implements it is legal and actually working.

As the documentation states the Cloneable interface does not declare the signature of the clone method. That method is inherently inherited in any class you declare from the Object class but it is protected by default. This is why you should weaken this constraint by making it public in the middle interface MyInterface that you declare.

Take a look at this hint given in Java doc:

Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

Upvotes: 6

SLaks
SLaks

Reputation: 887469

The Cloneable interfaces doesn't have any methods.
It's just a marker interface which the base Object.clone method (which is protected) checks for.

If you want a clone method, you need to declare it yourself.

Upvotes: 7

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

It's just because clone() isn't public in Object. If you declare public Object clone() in your interface -- in other words, if you make your first example like your second -- then your first example will work.

Upvotes: 1

Related Questions