「Java」thisキーワードで他コンストラクタ(constructor)を呼び出す方法
説明
thisでコンストラクタ内から他のコンストラクタを呼び出します
使用例
(1).クラスの定義
package com.arkgame.study;
public class ConstrutcorSample {
public ConstrutcorSample() {
System.out.println("コンストラクタ 引数なし");
}
public ConstrutcorSample(String target) {
//引数なしコンストラクタを呼び出し
this();
System.out.println("コンストラクタ 引数あり1個" + " 変数の初期値: " + target);
}
public ConstrutcorSample(String target, Integer cft) {
//引数なしコンストラクタを呼び出し
this();
System.out.println("コンストラクタ 引数あり2個" + "変数の初期値: " + target + " " + cft);
}
}
(2).thisで他のコンストラクタを呼び出し
package com.arkgame.study;
public class ConstructorExeDemo {
public static void main(String[] args) {
//引数 なし
ConstrutcorSample csA = new ConstrutcorSample();
System.out.println("*****************************");
//引数 1個
ConstrutcorSample csB = new ConstrutcorSample("atm");
System.out.println("*****************************");
//引数 2個
ConstrutcorSample csC = new ConstrutcorSample("shop", 25);
}
}
(3).実行結果
コンストラクタ 引数なし
*****************************
コンストラクタ 引数なし
コンストラクタ 引数あり1個 変数の初期値: atm
*****************************
コンストラクタ 引数なし
コンストラクタ 引数あり2個変数の初期値: shop 25