public class Hero {
String name;
int hp;
String email;
// コンストラクタ①:nameを引数に取る
public Hero(String name) {
this.hp = 100;
this.name = name;
this.email = "メールアドレスの入力がありません";
}
// コンストラクタ②:name と email の両方を引数に取る
public Hero(String name, String email) {
this.hp = 100;
this.name = name;
this.email = email;
}
// コンストラクタ③:引数なし(デフォルト値を設定)
public Hero() {
this("ダミー", "abc@example.com"); // コンストラクタ②を呼び出す
}
public void showInfo() {
System.out.println("名前: " + this.name);
System.out.println("HP: " + this.hp);
System.out.println("メール: " + this.email);
}
}
実行コードと出力結果
public class Main {
public static void main(String[] args) {
Hero h1 = new Hero("勇者"); // 名前のみ指定
Hero h2 = new Hero("戦士", "warrior@example.com"); // 名前とメール指定
Hero h3 = new Hero(); // 引数なしでデフォルト値を使用
h1.showInfo();
h2.showInfo();
h3.showInfo();
}
}
名前: 勇者
HP: 100
メール: メールアドレスの入力がありません
名前: 戦士
HP: 100
メール: warrior@example.com
名前: ダミー
HP: 100
メール: abc@example.com
注意
複数の引数を持つコンストラクタを連鎖的に定義する場合、後ろの引数から順にデフォルト値を設定していく設計が一般的であり、推奨される
public class Thief {
String name;
int hp;
int mp;
//1
public Thief (String name, int hp, int mp) {
this.name = name;
this.hp = hp;
this.mp = mp;
}
//2
public Thief (String name, int hp) {
this(name, hp, 5);
}
//3
public Thief (String name) {
this(name, 40); //mpは上の5が参照され書く必要はなし。hpの
//40のみ指定でOK
}
}