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,
This beacause the
Cloneableinterface is not a normal interface but more or less a tagging interface which ensures to the JVM that theclonemethod of the class that implements it is legal and actually working.As the documentation states the
Cloneableinterface does not declare the signature of theclonemethod. That method is inherently inherited in any class you declare from theObjectclass but it isprotectedby default. This is why you should weaken this constraint by making itpublicin the middle interfaceMyInterfacethat you declare.Take a look at this hint given in Java doc: