问题描述
通常,我只在构造函数中使用 this
.
我知道它用于标识参数变量(通过使用this.something
),如果它与全局变量具有相同的名称.
然而,我不知道 this
在 Java 中的真正含义是什么,如果我使用 this
而没有点 (.
).
this
引用当前对象.
每个非静态方法都在对象的上下文中运行.因此,如果您有这样的课程:
public class MyThisTest {私人内部;公共 MyThisTest() {这(42);//调用另一个构造函数}公共 MyThisTest(int a) {this.a = a;//将参数a的值赋给同名字段}公共无效 frobnicate() {int a = 1;System.out.println(a);//引用局部变量aSystem.out.println(this.a);//指的是字段aSystem.out.println(this);//引用整个对象}公共字符串 toString() {返回 "MyThisTest a=" + a;//指的是字段a}}
然后在 new MyThisTest()
上调用 frobnicate()
将打印
如此有效地将它用于多种用途:
- 澄清您在谈论一个字段,同时还有其他与字段同名的内容
- 将当前对象作为一个整体引用
- 在你的构造函数中调用当前类的其他构造函数
Normally, I use this
in constructors only.
I understand that it is used to identify the parameter variable (by using this.something
), if it have a same name with a global variable.
However, I don't know that what the real meaning of this
is in Java and what will happen if I use this
without dot (.
).
this
refers to the current object.
Each non-static method runs in the context of an object. So if you have a class like 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
}
}
Then calling frobnicate()
on new MyThisTest()
will print
1 42 MyThisTest a=42
So effectively you use it for multiple things:
- clarify that you are talking about a field, when there's also something else with the same name as a field
- refer to the current object as a whole
- invoke other constructors of the current class in your constructor
这篇关于“这个"是什么意思在爪哇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!