通常はコンストラクター内でのみ使用します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
つまり、実際には複数の用途に使用できます。
- フィールドと同じ名前のものがあるときに、フィールドについて話していることを明確にする
- 現在のオブジェクト全体を参照する
- コンストラクタ内で現在のクラスの他のコンストラクタを呼び出す