一、概述
通常我仅在构造函数中使用this
。
如果它与全局变量具有相同的名称,我了解它用于标识参数变量(通过使用this.something
),
我不知道this在
Java中的真正含义是什么,如果this
不使用点(.
),将会发生什么。
二、详解
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
}
}
new MyThisTest()
调用frobnicate()
会打印
1个 42 MyThisTest a = 42
因此,有效地将它用于多种用途:
- 区分方法内的局部变量和类的属性
- 整体引用当前对象
- 在构造函数中调用当前类的其他构造函数
如若转载,请注明出处:https://www.javaidea.cn/article/8252.html