The clone method and the Cloneable interface - 1

"Hi, Amigo!"

"Hi, Kim."

"I'm going to tell you about the clone() method."

"The point of this method is to clone an object, or in other words, to create a clone/copy/duplicate of the object."

"When this method is called, the Java virtual machine creates and returns a duplicate of the object it is called on.

The Object class's implementation of the clone method is very primitive: only one new object is created, and the values of the original object's fields are assigned to its fields.

If the copied object contains references to other objects, then those references will be copied. Duplicates of those objects will not be created."

"Hmm. That's not much to go on."

"The thing is, the Java virtual machine doesn't know which objects can or can't be cloned. For example, files can't be cloned. The same is true for a System.in stream."

"So, the question of full-fledged cloning was punted to a class's developers. "This is all similar to how the equals method is handled. There's even something comparable to hashCode: the Cloneable interface."

"The Cloneable interface is what's called a 'marker interface': it doesn't have any methods and is used to mark certain classes.

"If a class's developer believes objects of the class can be cloned, he marks it with this interface (i.e. makes the class implement Cloneable)."

"If the developer doesn't like the clone method's standard implementation, he must write his own that will create a duplicate object in the right way."

"When you call the clone() method, Java checks whether the object supports the Cloneable interface. If it does, then it clones the object using the clone() method; if not, it throws a CloneNotSupportedException."

"In other words, we must either override the clone method or make the class implement Cloneable?"

"Yes, but you still have to override the method. The clone() method is declared as protected, so it can only be called by classes in its package (java.lang.*) or their subclasses."

"I'm a little confused—so what do I need to do to clone an object?"

"If you want to use the Object class's «default» cloning method, you need to:

"a) Add the Cloneable interface to your class"

"b) Override the clone method and call the superclass's implementation within your implementation:"

class Point implements Cloneable
{
 int x;
 int y;

 public Object clone()
 {
  return super.clone();
 }
    }

"Or you can write a implementation of the clone method entirely on your own:"

class Point
{
 int x;
 int y;

 public Object clone()
 {
  Point point = new Point();
  point.x = this.x;
  point.y = this.y;
  return point;
 }
}

"That's an interesting method. I'm sure I'll use it. Occasionally…"