14.07.2013 Views

Contents - Cultural View

Contents - Cultural View

Contents - Cultural View

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

clone (Java method) 56<br />

2) Every class that has any data other than primitives that has to be cloned must contain a clone() function that<br />

handles it. This includes all objects and all primitives that are allocated with the 'new' command such as variable<br />

length arrays. (This assumes that the programmer wants the objects to be cloned (deep copy) and not just have their<br />

reference copied (shallow copy).)<br />

Example<br />

- since class Z has a reference to an object of another class, there needs to be specific code to clone that object.<br />

abstract public class X implements Cloneable {<br />

}<br />

public Object clone() throws CloneNotSupportedException {<br />

}<br />

return super.clone();<br />

abstract public class Y extends X { }<br />

public class ObjectABC implements Cloneable {<br />

}<br />

public Object clone() throws CloneNotSupportedException {<br />

}<br />

public class Z extends Y {<br />

}<br />

return super.clone();<br />

private ObjectABC someABC;<br />

public Object clone() throws CloneNotSupportedException {<br />

}<br />

public class test1 {<br />

}<br />

Z newZ = (Z) super.clone();<br />

newZ.someABC = (ObjectABC) someABC.clone();<br />

return newZ;<br />

public void function() throws CloneNotSupportedException {<br />

}<br />

Easy Solution<br />

Y varY1 = new Z();<br />

Y varY2 = (Y) varY1.clone();<br />

The easiest solution to this is to make the base class "implements Cloneable" and have the base class and all<br />

sub-classes contain the clone() method. When a class has data in it that must be cloned, adding a line or two to the<br />

clone() method is straight forward.<br />

Example<br />

abstract public class X implements Cloneable {<br />

public Object clone() throws CloneNotSupportedException {<br />

return super.clone();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!