Search code examples
javasuperclasscloneable

Cloneable behaviour


Java doc says -

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.

Which is why clone method in Object class is protected ? is that so ?

That means any class which doesn't implement cloneable will throw CloneNotSupported exception when its clone method is invoked.

I ran a test program

public class Test extends ABC implements Cloneable{

    @Override
    public Object clone() throws CloneNotSupportedException {
        System.out.println("calling super.clone");
            return super.clone();
    }

    public static void main(String[] args) {
        Test t = new Test();
        try{
        t.clone();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class ABC{

}

From Class Test's clone method super.clone is being invoked ?

Why doesn't it throw exception ?


Solution

  • Inheritance tree of the Test instance t looks like

    Object
      ABC
        Test
    

    Test also implements Cloneable which means that when you call the method super.clone() Object's clone method will be called. It checks if the instance t implements the Cloneable interface. Since it does implement the method doesn't throw an exception.