SE450: Clone: Full examples [7/32] Previous pageContentsNext page

To disallow cloning, make you class final and do not override clone().

public final class A { ... }

If your class is non-final and public, you either need to expect that a subclass will implement clone, or disallow cloning:

public class A {
  ...
  protected final Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }
}

To implement cloning:

file:IntegerStack.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package clone.stack;
public final class IntegerStack implements Cloneable {
  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--];
  }
  public Object clone() {
    try {
      IntegerStack result = (IntegerStack) super.clone();
      result.buffer = buffer.clone();
      return result;
    } catch (CloneNotSupportedException e) {
      // cannot happen
      throw new RuntimeException(e);
    }
  }
}

Previous pageContentsNext page