通常,我仅在构造函数中使用 this
。
我知道它用于标识参数变量(通过使用 this.something
),如果它与全局变量具有相同的名称。
但是,我不知道 this
在 Java 中的真正含义是什么,以及如果我使用不带点的 this
会发生什么(.
)。
最佳答案
this
指的是当前对象。
每个非静态方法都在对象的上下文中运行。因此,如果您有这样的类(class):
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
}
}
然后在 new MyThisTest()
上调用 frobnicate()
将打印
1 42 MyThisTest a=42
因此,您可以有效地将它用于多种用途:
- 当还有其他内容与字段同名时,请澄清您正在谈论一个字段
- 将当前对象作为一个整体引用
- 在构造函数中调用当前类的其他构造函数
关于java - Java中 "this"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59101504/