必要なのは、次のように、パラメーターCountry
を受け取り、それをフィールドに割り当てるコンストラクターを定義することです。
public class Country implements ICountry {
int stability = 2; // the default
public Country() {
// no parameters, no assignments
}
public Country(int stability) {
// declares parameter, assigns to field
this.stability = stability;
}
}
次に、次のように、このクラスの複数のインスタンスを作成できます。
Country unitedKingdom = new Country(); // 2 is the value of stability, taken from the default
Country poland = new Country(3); // 3 is the value of stability
2つのコンストラクターが必要な理由は、パラメーターが指定されていない場合はパラメーターのないバージョン(「デフォルト」または「暗黙の」コンストラクター)が生成されますが、コンストラクターを指定すると生成されないためです。もう。
デフォルトのコンストラクターの代替の同等の構文は、次のようになります。
public class Country implements ICountry {
int stability; // declare field, but don't assign a value here
public Country() {
this.stability = 2; // instead assign here, this is equivalent
}
}
このバージョンと以前のバージョンのデフォルトコンストラクターはどちらも同じ効果をもたらしますが、一般的には好みの問題です。
示した構文を使用する言語があり、それらは「名前付きパラメーター」と呼ばれますが、Javaにはありません。