私は最近 Java を読んでいて、何か (イディオム?) に新しいものに出くわしました: プログラムでは、複数のコンストラクターを持つクラスには、常に空のコンストラクターも含まれます。例えば:
public class Genotype {
private boolean bits[];
private int rating;
private int length;
private Random random;
public Genotype() { // <= THIS is the bandit, this one right here
random = new Random();
}
/* creates a Random genetoype */
public Genotype(int length, Random r) {
random = r;
this.length = length;
bits = new boolean[length];
for(int i=0;i<length;i++) {
bits[i] =random.nextBoolean();
}
}
/* copy constructor */
public Genotype(Genotype g,Random r) {
random = r;
bits = new boolean[g.length];
rating = g.rating;
length = g.length;
for(int i=0;i<length;i++) {
bits[i] = g.bits[i];
}
}
}
最初のコンストラクターは「実際の」コンストラクターではないようです。どの場合でも、他のコンストラクターのいずれかが使用されるようです。では、なぜそのコンストラクターがまったく定義されているのでしょうか。