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) 55<br />

Alternatives<br />

There are alternatives to clone(), notably the use of a copy constructor - a constructor that accepts as a parameter<br />

another instance of the same class - or a factory method. These methods are not always adequate when the concrete<br />

type of the cloned object is not known in advance. (However, clone() is often not adequate either for the same<br />

reason, as most abstract classes do not implement a public clone() method.)<br />

Also the use of serialization and deserialization is another alternative to using clone.<br />

clone() and the Singleton pattern<br />

When writing a class using the Singleton pattern, only one instance of that class can exist at a time. As a result, the<br />

class must not be allowed to make a clone. To prevent this, override the clone() method using the following code:<br />

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

}<br />

throw new CloneNotSupportedException();<br />

(Note: This is only necessary if a superclass implements a public clone() method, or to prevent a subclass from using<br />

this class's clone() method to obtain a copy. Since classes don't usually inherit a public clone() method (Object<br />

doesn't have a public clone() method), it is usually unnecessary to explicitly implement a non-functional clone()<br />

method.<br />

clone() and class hierarchy<br />

When working with the clone() in a hierarchy of classes, there are several things that must be handled properly.<br />

1) Every type reference that needs to call the clone function must have a clone() method in its own class or a publicly<br />

accessible clone() method in its parent classes. That means that if you want to clone a reference to an abstract base<br />

class, either the base class must have a clone() method, or one of its parents must have a publicly accessible clone()<br />

method.<br />

Example<br />

- since varY1 is of type Y, then Y must have clone(), or a parent of Y must have clone()<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 Z extends Y { }<br />

public class test1 {<br />

}<br />

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

}<br />

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

Y varY2 = (Y) varY1.clone();

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

Saved successfully!

Ooh no, something went wrong!