LoginSignup
2
2

thisには2つの顔がある

Last updated at Posted at 2023-12-09

thisには2つの用途があると学んだので備忘のため残す。

1つめ
コンストラクタはオーバーロードして複数定義できる。
オーバーロードされたコンストラクタから別のコンストラクタを呼び出すにはthisを使う。

public class Sample{
	public Sample(){
		this(null,0);//この引数がオーバーロードされたコンストラクタに渡される。
        //thisの前には何も記述しちゃいけない
      
	}
	public Sample(String str, int num){
		System.out.println("OK");
	}
}

2つめ
インスタンスそのものを表す参照に入れる特別な変数

public class Sample{

	public String str;
	public int num;

	public Sample(String str,int num){
		this.str = str; //生成したインスタンスのstrに値を入れてる
		this.num = num; //生成したインスタンスのnumに値を入れてる
	}
2
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2