开发者

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 te开发者_JAVA百科stM();
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜