简体   繁体   中英

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,

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM