Java Reference
In-Depth Information
CloneNotSupportedException it may receive from other objects it
tries to clone. Or a class may have the ability to be cloned itself
but not require that all subclasses also have the ability to be
cloned.
Allow subclasses to support clone but don't publicly support it.
Such a class doesn't implement Cloneable , but if the default im-
plementation of clone isn't correct, the class provides a protected
clone implementation that clones its fields correctly.
Forbid clone . Such a class does not implement Cloneable and
provides a clone method that always throws CloneNotSupportedEx-
ception .
Object.clone checks whether the object on which it was invoked imple-
ments the Cloneable interface and throws CloneNotSupportedException if it
does not. Otherwise, Object.clone creates a new object of exactly the
same type as the original object on which clone is invoked and initial-
izes the fields of the new, cloned object to have the same values as the
fields of the original object. When Object.clone is finished, it returns a
reference to the new object.
The simplest way to make a class that can be cloned is to declare that it
implements the Cloneable interface, and override the clone method, re-
declaring it to be public:
public class MyClass extends HerClass implements Cloneable {
public MyClass clone()
throws CloneNotSupportedException {
return (MyClass) super.clone();
}
// ...
}
Any other code can now make a clone of a MyClass object. In this simple
case, all fields of MyClass will be assigned by Object.clone into the new
 
Search WWH ::




Custom Search