• Post Reply Bookmark Topic Watch Topic
  • New Topic

clone()  RSS feed

 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have a class:



What is the difference/preference between:



and


[ November 07, 2008: Message edited by: Red Smith ]
 
arulk pillai
Author
Ranch Hand
Posts: 3417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should override the clone() method very judiciously. Implementing a properly functioning clone method is complex and it is rarely necessary. You are better off providing some alternative means of object copying ( or simply not providing the capability. A better approach is to provide a copy constructor or a static factory method in place of a constructor.




or




The clone() method can be disabled as follows:

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calling super.clone is not required. It's just used often because Object's implementation copies all values for you, and it removes a lot of work for you if you have many fields.

If you look at the contract of clone(), it doesn't say you need super.clone(). In fact, there are no real requirements. The clone may be of a different class, it may even be different, but it can also be "this". (Although usually it is the same class and equal but not "this".)

However, super.clone() has one advantage for non-final classes - it returns an instance of the exact same class. Let's take your example:

So once you're using the "new A(value)" solution, then all subclasses X must use "new X(...)" as well if they want to return X instead of A.

Now if you would use super.clone() the cast would be safe and you could return X easily.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!