1 Reply Latest reply: Dec 6, 2012 9:22 AM by gimbal2 RSS

    What are all the myths around Cloneable interface and clone() method?

    nitul.kukadia
      There have been other questions similar to this: Why is #clone() not in the Cloneable interface? and others.

      But this question is not the same or duplicate. It tries to go in the logical aspects of what wrong would happen if something other than this would have been done.

      Question 1) Why Cloneable interface at the first place ?

      Question 2) Why is Cloneable interface marker interface or why not keep clone() method in it ?

      Question 3) Why not create a Cloneable class rather than markable interface ?

      Question 4) Why is default implementation of clone() method in Object ?

      Question 5) So why is clone() method protected in Object ?
        • 1. Re: What are all the myths around Cloneable interface and clone() method?
          gimbal2
          nitul.kukadia wrote:
          There have been other questions similar to this: Why is #clone() not in the Cloneable interface? and others.

          But this question is not the same or duplicate. It tries to go in the logical aspects of what wrong would happen if something other than this would have been done.

          Question 1) Why Cloneable interface at the first place ?
          Who cares about the why? What matters is that it is like the way it is and it is not going to change. Only the people who designed it can really answer it; that was more than 15 years ago. I'm pretty sure that if you asked those people in an interview today they'd answer "yeah, I would do it differently today".
          Question 2) Why is Cloneable interface marker interface or why not keep clone() method in it ?
          No need; all objects inherit from Object and Object has the clone() method.
          Question 3) Why not create a Cloneable class rather than markable interface ?
          Because you can extend only one class and implement many interfaces. Making it a class would severely limit you. Making it a class would not change anything anyway - it would still be empty.
          Question 4) Why is default implementation of clone() method in Object ?
          Convenience? Basically the same as 1), the why can only really be answered by the people who designed it.
          Question 5) So why is clone() method protected in Object ?
          Again a why. Because some group of people decided that it should be so.

          My own take on it is that this is a trade off between adhering to an interface contract (Cloneable) while providing a default implementation anyway (Object.clone()). But I can only guess. I don't care about the why in any case, I only care how to properly do it. Which is quite easy and well documented.