前のエントリのJavaScriptサンプルに対応するJavaコードです。
/* Counter.java */public class Counter {
public static final int UPPER_BOUND = 10;
public static final int MAX_COUNTERS = 3;
public static int counters = 0;public int value;
public Counter(int initValue) {
if (counters >= MAX_COUNTERS) {
throw new RuntimeException("too many counters.");
}
if (0 <= initValue && initValue < UPPER_BOUND) {
value = initValue;
} else {
throw new RuntimeException("Illegal initial value:" + initValue);
}
counters++;
}
public Counter() {
this(0);
}public void inc() {
if (value + 1 >= UPPER_BOUND) {
throw new RuntimeException("counter overflow.");
}
value++;
}
public void dec() {
if (value <= 0) {
throw new RuntimeException("counter underflow.");
}
value--;
}
}