0
votes

Please don't close as duplicate. I know there are multiple threads on this topic but none of them answers my question.

I am still struggling to understand why do we need Cloneable interface in java. If we want to create copy of an object, we can simply override clone method from Object class and call super.clone(). Since clone method in Object class is native, we don't know if the native implementation checks for instanceOf Cloneable and then create a copy else throw CloneNotSupportedException.

I know it's not a good practice to override clone() method to create a copy and should go for copy constructor instead, but still I want to know is the existence of Cloneable marker interface justified.

1
It's part of the object cloning mechanism designed into the Java language, as described in the API documentation for Cloneable. And yes, it's not the most elegant design, as recognized long ago and explained, for example, in the "Effective Java" book.Rogério

1 Answers

0
votes

Whether an object implements Cloneable or not only matters if the built-in Object.clone() method is called (probably by some method in your class that calls super.clone()). If the built-in Object.clone() method is called, and the object does not implement Cloneable, it throws a CloneNotSupportedException. You say "we don't know" whether the Object.clone() method does that -- we do -- the documentation for Object.clone() method in the Java class library explicitly promises it, and it describes in detail the cloning operation that the method performs.

If you implement a cloning method that does not call up to Object.clone(), then whether the object implements Cloneable or not has no effect.