SE450: Java classes: cloning implementation [19/22] Previous pageContentsNext page

Simple:


public class MyClass extends HerClass implements Clonable {
  public Object clone throws CloneNotSupportedException {
    return super.clone();
  }
  // ...
}
But what about

public class IntegerStack implements Clonable {
  private int[] buffer;
  private int top;
  
  public IntegerStack(int maxContents) {
   buffer = new int[maxContents];
   top = -1;
  }
  
  public void push(int val) {
    buffer[++top] = val;
  }

  public int pop() {
    return buffer[top--];
  }

}

What does the default clone method do?

Fix this by overriding clone


public Object clone() {
  try {
    IntegerStack nObj = (IntegerStack)super.clone();
    nObj.buffer = (int[])buffer.clone();
    return nObj;
  } catch (CloneNotSupportedException e) {
    // cannot happen since we and arrays support clone
    throw new Error(e.toString());
  }
}

To disallow cloning:


public final Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
}

There are alternatives:

Previous pageContentsNext page