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 ?
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 interfaceCloneable
, so calling theclone
method on an object whose class isObject
will result in throwing an exception at run time.