You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
General <strong>Java</strong> Questions I<br />
2. override the method clone(), so that it<br />
a. becomes public<br />
b. calls super.clone()<br />
c. if necessary, clones any members, or<br />
d. if a member can't be cloned, creates a new instance.<br />
Simple example:<br />
public MyClass implements Cloneable {<br />
int someNumber;<br />
String someString;<br />
public Object clone() {<br />
// primitives and Strings are no<br />
// problem<br />
return super.clone();<br />
}<br />
}<br />
In this case the method clone() of the class MyClass returns a new instance of<br />
MyClass, where all members have exactly the same value. That means, the object<br />
reference 'someString' points to the same object. This is called a shallow<br />
copy. In many cases this is no problem. Strings are immutable and you do not<br />
need a new copy. But if you need new copies of members, you have to do it in<br />
the clone() method. Here is another simple example:<br />
public class SomeMember implements Cloneable {<br />
long someLong;<br />
}<br />
public Object clone() {<br />
return super.clone();<br />
}<br />
public AnotherClass extends MyClass {<br />
SomeMember someMember;<br />
}<br />
public Object clone() {<br />
AnotherClass ac = (AnotherClass)(super.clone());<br />
if (someMember != null) {<br />
ac.someMember = (SomeMember)(someMember.clone());<br />
}<br />
return ac;<br />
}<br />
Note that the class AnotherClass, that extends MyClass, automatically becomes<br />
Cloneable, because MyClass is Cloneable.<br />
file:///F|/350_t/350_tips/general_java-I.htm (13 of 31) [2002-02-27 21:18:17]