简体   繁体   English

Java接口扩展了Cloneable

[英]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? Cloneable会发生什么?

Thanks, 谢谢,

The Cloneable interfaces doesn't have any methods. Cloneable接口没有任何方法。
It's just a marker interface which the base Object.clone method (which is protected ) checks for. 它只是一个标记接口, 基础Object.clone方法protected )检查。

If you want a clone method, you need to declare it yourself. 如果需要clone方法,则需要自己声明。

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. 这是因为Cloneable接口不是普通接口,而是或多或少的标记接口,它确保JVM实现它的类的clone方法是合法的并且实际上正常工作。

As the documentation states the Cloneable interface does not declare the signature of the clone method. 正如文档所述, Cloneable接口不会声明clone方法的签名。 That method is inherently inherited in any class you declare from the Object class but it is protected by default. 该方法本质上是在您从Object类声明的任何类中继承的,但默认情况下protected This is why you should weaken this constraint by making it public in the middle interface MyInterface that you declare. 这就是为什么你应该通过在你声明的中间接口MyInterfacepublic它来削弱这个约束。

Take a look at this hint given in Java doc: 看看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. 即使反射调用clone方法,也无法保证它会成功。

It's just because clone() isn't public in Object . 这只是因为clone()在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. 如果你在界面中声明public Object clone() - 换句话说,如果你的第一个例子就像你的第二个 - 那么你的第一个例子就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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