Chapter 16: Exploring java.lang 413
Using clone( ) and the Cloneable Interface
Most of the methods defined byObjectare discussed elsewhere in this book. However, one
deserves special attention:clone( ). Theclone( )method generates a duplicate copy of the
object on which it is called. Only classes that implement theCloneableinterface can be cloned.
TheCloneableinterface defines no members. It is used to indicate that a class allows a
bitwise copy of an object (that is, aclone) to be made. If you try to callclone( )on a class that
does not implementCloneable, aCloneNotSupportedExceptionis thrown. When a clone
is made, the constructor for the object being cloned isnotcalled. A clone is simply an exact
copy of the original.
Cloning is a potentially dangerous action, because it can cause unintended side effects.
For example, if the object being cloned contains a reference variable calledobRef,then when
the clone is made,obRefin the clone will refer to the same object as doesobRefin the original.
If the clone makes a change to the contents of the object referred to byobRef,then it will be
changed for the original object, too. Here is another example: If an object opens an I/O stream
and is then cloned, two objects will be capable of operating on the same stream. Further, if
one of these objects closes the stream, the other object might still attempt to write to it, causing
an error. In some cases, you will need to override theclone( )method defined byObjectto
handle these types of problems.
Because cloning can cause problems,clone( )is declared asprotectedinsideObject.
This means that it must either be called from within a method defined by the class that
implementsCloneable, or it must be explicitly overridden by that class so that it is public.
Let’s look at an example of each approach.
Method Description
final Class<?> getClass( ) Obtains aClassobject that describes the invoking
object.
int hashCode( ) Returns the hash code associated with the invoking
object.
final void notify( ) Resumes execution of a thread waiting on the
invoking object.
final void notifyAll( ) Resumes execution of all threads waiting on the
invoking object.
String toString( ) Returns a string that describes the object.
final void wait( )
throws InterruptedException
Waits on another thread of execution.
final void wait(longmilliseconds)
throws InterruptedException
Waits up to the specified number ofmillisecondson
another thread of execution.
final void wait(longmilliseconds,
intnanoseconds)
throws InterruptedException
Waits up to the specified number ofmilliseconds
plusnanosecondson another thread of execution.
TABLE 16-14 The Methods Defined byObject(continued)