An Example of an Externally Immutable and Internally Mutable Class - Java Object Oriented Design

Java examples for Object Oriented Design:Class

Description

An Example of an Externally Immutable and Internally Mutable Class

Demo Code

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

    public MyClass(int value) {
        this.value = value;
    }       /*from   ww  w .j av  a2 s  .  c o  m*/

    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