Reputation: 1723
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 ?
Upvotes: 1
Views: 73
Reputation: 48307
Since Cloneable is an Interface, ...how it is possible to access a method directly ?
no you are not; Clonable interface is a Tag interface (has no methods), and the method Clone you are invoking comes from the Object class...
the clonable interface is just empty
Upvotes: 2
Reputation: 477824
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.
Upvotes: 4
Reputation: 2674
Cloneable
is a very special interface and does not have any methods defined. It is only used to indicate that this class can be cloned. If you wouldn't implement Cloneable the super.clone()
would throw a CloneNotSupportedException
.
Upvotes: 2