Copy constructor versus cloning. Why shouldn't I consider Cloneable?

I was reading this answer and it mentioned a link where the author explains why we shouldn't use Cloneable. But, still doubt what was said there

If I have a Cloneable array, you might think that I can escape that array and clone each element to make a deep copy of the array, but I cannot. You cannot overlay something on Cloneable and call the clone method as Cloneable does not have a public clone method and also not Object . If you try to apply to Cloneable and call clone, the compiler will say that you are trying to call a protected clone method on an object.

But here I did

        Init s = Init.getInstance(); // getting instance
        int count=0;
        Cloneable[] v = new Cloneable[5]; // creating array
        Init x = s;
        Init y = new Init(s);
        try {
            while (count < 5) {
                v[count++] =  (Cloneable) s.clone(); // casting it.
            }

            s.setClassName("Example");
            System.out.println(((Init) v[2]).getClassName()); // Displaying.
        } catch (CloneNotSupportedException ex) {
            ex.printStackTrace();
        }

      

I managed to create a Cloneable array and I did what the author said would throw an error. Or am I misunderstanding the author's expression? Anyone please help me understand the reason for choosing Copy Constructor over Cloneable.

+3


source to share


1 answer


You dont throw s

in Cloneable

and then call clone()

on it.

Instead, you call s.clone()

and then return the result to Clonable

. You can do this because it s

has a type Init

and Init

a method public clone()

.

Do it instead and you will see the compiler scream,

 v[count++] =  ((Cloneable) s).clone();

      



Now let's say that you want to clone an array (you obviously only know the array Cloneable

, which means you don't know its actual type.

Cloneable[] cloneArray = new Cloneable[5];
cloneArray[i] = new Init(); // Let say it initialized with different type objects but all `Cloneable`.

for (Cloneable object : cloneArray) {
      object.clone(); // Compiler wont allow it. And you don't know what type it is.
}

      

So you basically can't deeply clone a Cloneable array.

+4


source







All Articles