Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

clone method

 
ramchander yshetti
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai,
how to implement the copy constructor using clone() method, please given me a simple example code..
have a good day.. bye.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't implement a copy constructor using clone(). However, clone() and copy constructors can sometimes be used for similar purposes.

A copy constructor is a constructor that takes an object of the same class and copies the data from that object into the object being constructed.

The clone() method is an instance method of every object. When you execute it on an object, if that object implements the marker interface Cloneable, a copy of the object is returned.

The basic clone() method does a shallow copy. You can override it to do a deep(er) copy. A copy constructor can be coded to do shallow or deep copy, as you require.

Personally, I think the clone() feature of Java was badly designed, and I rarely use it, except with arrays, where it does seem genuinely useful.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
PC: You can't implement a copy constructor using clone()..

Well you can't clone the instance passed as a parameter to the copy constructor, but you can clone all the mutable fields if they implement Cloneable.

Although I agree with your point about the Clone implementation in Java. If I want the same functionality I typically use a custom interface.

[ August 03, 2006: Message edited by: Garrett Rowe ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic