Path: csiph.com!au2pb.net!feeder.erje.net!1.eu.feeder.erje.net!news-1.dfn.de!news.dfn.de!cache.uni-koblenz.de!not-for-mail From: Tassilo Horn Newsgroups: comp.lang.java.programmer Subject: Re: What goes wrong with cloning here Date: Fri, 23 Oct 2015 18:12:54 +0200 Organization: University Koblenz-Landau Campus Koblenz Lines: 25 Message-ID: <87pp05k1h5.fsf@gnu.org> References: <87oafplh3t.fsf@Equus.decebal.nl> NNTP-Posting-Host: 2.161.212.107 Mime-Version: 1.0 Content-Type: text/plain X-Trace: cache.uni-koblenz.de 1445616775 20439 2.161.212.107 (23 Oct 2015 16:12:55 GMT) X-Complaints-To: news@cache.uni-koblenz.de NNTP-Posting-Date: Fri, 23 Oct 2015 16:12:55 +0000 (UTC) User-Agent: Gnus/5.130014 (Ma Gnus v0.14) Emacs/25.0.50 (gnu/linux) Cancel-Lock: sha1:+OOE+1ExEIfI4T0z7nek5CwlhJE= Xref: csiph.com comp.lang.java.programmer:32932 Cecil Westerhof writes: > When I in class A change a field from class B in the clone, the field > in the original is also changed. That should not happen. > > public class A implements Cloneable { > private B key; > ^^^ > public Object clone() throws CloneNotSupportedException { > A clone = (A) super.clone(); > B newKey = new B(); > B oldKey = getKey(); > > newKey.setA(oldKey.getA()); > newKey.setB(oldKey.getB()); > newKey.setC(oldKey.getC()); > newKey.setD(oldKey.getD()); > clone.setKey(key); ^^^ I guess here you want to set the key of the clone to newKey, not to this.key. Bye, Tassilo