Java の「this」の意味は何ですか? 質問する

Java の「this」の意味は何ですか? 質問する

通常はコンストラクター内でのみ使用しますthis

this.somethingグローバル変数と同じ名前を持つ場合、パラメータ変数を識別するために( を使用)使用されることを理解しています。

しかし、Java での の本当の意味が何なのか、ドット ( ) なしでthis使用すると何が起こるのかはわかりません。this.

ベストアンサー1

this現在のオブジェクトを参照します。

各非静的メソッドはオブジェクトのコンテキストで実行されます。そのため、次のようなクラスがあるとします。

public class MyThisTest {
  private int a;

  public MyThisTest() {
    this(42); // calls the other constructor
  }

  public MyThisTest(int a) {
    this.a = a; // assigns the value of the parameter a to the field of the same name
  }

  public void frobnicate() {
    int a = 1;

    System.out.println(a); // refers to the local variable a
    System.out.println(this.a); // refers to the field a
    System.out.println(this); // refers to this entire object
  }

  public String toString() {
    return "MyThisTest a=" + a; // refers to the field a
  }
}

次に呼び出すfrobnicate()new MyThisTest()印刷されます

1
42
私のこのテスト a=42

つまり、実際には複数の用途に使用できます。

  • フィールドと同じ名前のものがあるときに、フィールドについて話していることを明確にする
  • 現在のオブジェクト全体を参照する
  • コンストラクタ内で現在のクラスの他のコンストラクタを呼び出す

おすすめ記事