Forums Register Login

Implementation of cloning

+Pie Number of slices to send: Send
How do we implement cloning for a class? In what scenario, can we do that?

Is there any relation between implementations of cloning and equals()?
+Pie Number of slices to send: Send
 

How do we implement cloning for a class?



Simply override the clone() method as defined in Object. You probably want to implement the Cloneable interface, as well.

In what scenario, can we do that?



You can do that in any scenario in which you want to be able to duplicate an instance of a given class. In addition, if you are making extensive use of Cloneable objects but, specifically, want one (or a few) classes to be non-Cloneable, you might consider implementing the clone method and throwing a CloneNotSupportedException. I suspect you'd have to have a very good reason for doing so, though, as it could be confusing.

Is there any relation between implementations of cloning and equals()?



In general, x.clone().equals(x).

However, that isn't always true. Check out the API Spec for Object for more details.
+Pie Number of slices to send: Send
Thanks for the reply.

How does that work for protected classes?
Can we override the clone() method even for final & abstract classes as well?
+Pie Number of slices to send: Send
 

Originally posted by Naina Si:
How does that work for protected classes?



Do you really mean protected classes or are you referring to the fact that clone() is defined as a protected method? You're free to override any method as long as the new method's access modifier is equally or less restrictive than the original. So, for a protected method, you can override that with a protected or a public method.

Can we override the clone() method even for final & abstract classes as well?



Sure.

For an abstract class, if you have data members defined within the abstract class and you want the subclasses to be cloneable, you'll probably want to make the abstract class cloneable, as well.
today's feeble attempt to support the empire
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 710 times.
Similar Threads
Clone problem
singleton object
Creating a copy of an object
What is cloning in java
When and why to use Cloneable interface in java?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:19:41.