1

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 ?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
SnuKies
  • 1,578
  • 1
  • 16
  • 37

3 Answers3

4

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

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.

findusl
  • 2,454
  • 8
  • 32
  • 51
  • Could you expand your answer further and tell me how could it throw an exception if a class is not implemented ? – SnuKies Apr 03 '17 at 15:00
  • You mean how the java framework checks if a class implements Cloneable in their Object.clone() method? – findusl Apr 03 '17 at 15:04
  • @findusl: no. By `implements Cloneable` you specify yourself that the object can be cloned. It is up to you to implement it. But you specify a "contract" that `clone()` will succeed. – Willem Van Onsem Apr 03 '17 at 15:05
  • @findusl Yes, that is what I am curious about My feeling is that they check with `instanceof` – SnuKies Apr 03 '17 at 15:08
  • @SnuKies generally you can check if something implements an Interface with instanceof. However clone is a native method and since there is some magic going on here to copy all attributes of the class I would assume they use something more special – findusl Apr 03 '17 at 15:09
2

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

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97