2

I know this is very similar to this SO question, but all the answers in that question only talk about the CloneNotSupportedException being thrown without the Clonable Interface.

But I would like to know why was it implemented in that way.

If a class overrides the clone() method and calls super.clone() it automatically means that the Class intends to clone the object.

And since clone() is a protected method in Object class, no one can call clone() on an instance if the instance's class didn't intend for clone() to be called. So what purpose does Cloneable interface actually have?

I thought it's for superclasses to prevent a subclass from calling clone, but it turns out wrong as well.

For eg:

the below code clones the object properly and what more, the field of the super class is also copied even though the super class has not implemented Cloneable interface

public class Test extends Test1 implements Cloneable {
    private int val;
    public static void main(String[] args) {
        Test test1 = new Test();
        test1.val = 15;
        test1.val1 = 20;

        Test test2 = test1.clone();

        System.out.println(test1.val);
        System.out.println(test1.val1);
        System.out.println(test2.val);
        System.out.println(test2.val1);
    }

    @Override
    protected Test clone() {
        try {
            return (Test) super.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}
class Test1 {
    public int val1;
}

Prints: 15 20 15 20.

Also, the Java doc of clone method 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.

But since clone() is a protected method in Object, how will it be possible for anyone to call the clone() method of an Object type object??

Am I missing anything obvious here??

Community
  • 1
  • 1
Codebender
  • 14,221
  • 7
  • 48
  • 85
  • 1
    There were a lot of bad decisions made with regards to Cloneable, and they have been extensively discussed. You'll be better off using your energy on something useful. – Kayaman Jun 26 '15 at 12:30
  • `.clone()` is broken, always has been, you should never use it, why it is broken is a long torrid story well documented in the duplicate and on the internet in general. If you really need to be able to duplicate an object, make it immutable or you can implement your own `copy` method or constructor. –  Jun 26 '15 at 12:31

0 Answers0