Using a Copy Constructor to Correctly Implement an Immutable Class - Java Object Oriented Design

Java examples for Object Oriented Design:Class

Description

Using a Copy Constructor to Correctly Implement an Immutable Class

Demo Code

class MyClass {/*  ww  w.j av  a 2  s.co m*/
  private final IntHolder valueHolder;

  public MyClass(int value) {
    this.valueHolder = new IntHolder(value);
  }

  public MyClass(IntHolder holder) {
    // Must make a copy of holder parameter
    this.valueHolder = new IntHolder(holder.getValue());
  }

  /* Rest of the code goes here... */
}

class IntHolder {
  private final int value;
  private int halfValue = Integer.MAX_VALUE;

  public IntHolder(int value) {
    this.value = value;
  }

  public int getValue() {
    return value;
  }

  public int getHalfValue() {
    // Compute half value if it is not already computed
    if (this.halfValue == Integer.MAX_VALUE) {
      // Cache the half value for future use
      this.halfValue = this.value / 2;
    }
    return this.halfValue;
  }
}

Related Tutorials