next up previous contents
Next: Packages Up: Java Interlude 2 Parameter Previous: Parameter passing in Java   Contents

Cloning

The root class Object in Java provides a method

  Object clone(Object o)

that makes a bit-wise copy of its argument. Making a bit-wise copy is fine if the the object being copied consists only of scalars. However, if it has nested objects (like Date inside Employee), the bitwise copy will copy the reference to the nested object Date so the clone will accidentally have a reference to a non-cloned internal component. We should, instead, recursively clone the internal object.

To ensure that a programmer is aware of the perils of using the clone method, Java requires that any class that invokes clone must implement the interface Cloneable. To use clone in Employee, we must write

  class Employee implements Cloneable{
    ...
  }

(Technically, we also need to redefine clone to be a public method. To understand this, we need to look at accessibilities other than public and private in Java, which we will do shortly.)

What does the interface Cloneable specify? Nothing! It is an empty interface, also called a marker interface that merely allows the method clone() to check if the class in which it is being invoked has been written by a ``thoughtful'' programmer who has understood the perils of making a bit-wise copy and (hopefully) taken necessary steps to make it work correctly.

The code for the method clone would contain a check something like the following:

  Object clone(Object o){
    if (o instanceof Cloneable){
       ... // go ahead and clone
    }else{
       ... // complain and quit
    }
  }


next up previous contents
Next: Packages Up: Java Interlude 2 Parameter Previous: Parameter passing in Java   Contents
Madhavan Mukund 2004-04-29