Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: markspace <-@.> Newsgroups: comp.lang.java.help Subject: Re: clone() and Cloneable Date: Wed, 05 Oct 2011 09:24:01 -0700 Organization: A noiseless patient Spider Lines: 48 Message-ID: References: <9852a7f5-75e0-49e9-9538-93824d185421@b6g2000vbz.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 5 Oct 2011 16:24:04 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="XjIWM99mD7Ijfdu600oVPA"; logging-data="15862"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/OyXfvPfCmvPDGesjYo+k3yZIHbwJbZYk=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20110929 Thunderbird/7.0.1 In-Reply-To: <9852a7f5-75e0-49e9-9538-93824d185421@b6g2000vbz.googlegroups.com> Cancel-Lock: sha1:tx5HuhSD3to2cahg6ebZdEg/V98= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.help:1192 On 10/5/2011 5:44 AM, John Goche wrote: > > Hello, > > What are the advantages of implementing the Cloneable > interface as opposed to a standard copy constructor perhaps > called clone() with no Cloneable interface in the class declaration? > One important difference is clone() is polymorphic. public class Point { private double x, y; // getters/setters elided. } public class ColorPoint extends Point { Color color; // getter/setter elided. } If you make a copy constructor for Point, you have to do the same for ColorPoint. But if you make Point Clonable, you don't have to do anything for ColorPoint. Its private field will still be copied by the clone() call. public class Point { private double x, y; // getters/setters elided. public Point clone() { try { return (Point) super.clone(); } catch( CloneNotSupportedExcetpion x ) { // cannot happen } } } Now clone() is properly supported for all classes that inherit from Point. Its children don't have to have any extra code to support clone() either, it's all done in the super class. Using Java copy-like constructors (Java doesn't really have copy constructors like C++ does), you'll have to implement extra code in each child to support the copy.