wood burning stoves 2.0
The moose likes Java in General and the fly likes clone method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "clone method" Watch "clone method" New topic

clone method

ramchander yshetti
Ranch Hand

Joined: Apr 22, 2006
Posts: 97
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

Joined: Oct 30, 2001
Posts: 1970
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.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
I agree. Here's the link: http://aspose.com/file-tools
subject: clone method
jQuery in Action, 3rd edition