• Post Reply Bookmark Topic Watch Topic
  • New Topic

Implementation of cloning  RSS feed

 
Naina Si
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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()?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Naina Si
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.

How does that work for protected classes?
Can we override the clone() method even for final & abstract classes as well?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!