SnuKies
SnuKies

Reputation: 1723

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 ?

Upvotes: 1

Views: 73

Answers (3)

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...

enter image description here

the clonable interface is just empty

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

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 interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

Upvotes: 4

findusl
findusl

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

Related Questions