Search code examples
javainterfacecloneable

Why it is possible to directly use Interface's method


I was reading about java and saw this code :

public class Person implements Cloneable{
    public Object Clone(){
        Object obj = null;
        try{
            obj = super.clone();
        }
        catch(CloneNotSupportedException ex){
        }
        return obj;
    }
}

Since Cloneable is an Interface, how it is possible to access a method directly ?


Solution

  • The super.clone() does not redirect to the Cloneable interface. Cloneable simply states that the object is supposed to be "cloneable". It does not specifies any methods (see the documentation).

    If you do not provide a superclass yourself, the superclass of Person is Object. Object has a Object clone() method itself (that raises an error).

    So what happens here is that it calls the clone() of the superclass. If you do not provide a superclass (with extends), it will call the clone() of Object that raises an CloneNotSupportedException. Otherwise it will return null here.

    In this case super.clone() will thus throw the CloneNotSupportedException since in the specifications of Object.clone():

    The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.