ProgressionとFibonacciProgressionの2つのクラスがありますが、FibonacciProgressionは、以下のように4と6でprintメソッドが呼び出されたときに予期しない結果を出力します。なぜこれなのか誰かが説明できますか?
public class Progression {
protected long first;
protected long cur;
Progression() {
cur = first = 0;
}
protected long firstValue() {
cur = first;
return cur;
}
protected long nextValue() {
return ++cur;
}
public void printProgression(int n) {
System.out.print(firstValue());
for (int i = 2; i <= n; i++) {
System.out.print(" " + nextValue());
}
System.out.println();
}
public static void main (String[] args) {
Progression prog = new Progression();
System.out.println("Default Progression: ");
prog.printProgression(10);
}
}
と..
public class FibonacciProgression extends Progression {
protected long prev;
FibonacciProgression(long value1, long value2) {
first = value1;
prev = value2 - value1;
}
FibonacciProgression() {
this(0,1);
}
protected long nextValue() {
long temp = prev;
prev = cur;
cur += temp;
return cur;
}
public static void main (String[] args) {
Progression fibProg = new FibonacciProgression(2,5);
System.out.println("Default Progression: ");
fibProg.printProgression(4);
fibProg.printProgression(6);
}
}