What is the meaning of quot;thisquot; in Java?(“这个是什么意思?在 Java 中?)
问题描述
通常,我只在构造函数中使用 this
.
我知道它用于识别参数变量(通过使用 this.something
),如果它与全局变量具有相同的名称.
但是,我不知道 this
在 Java 中的真正含义是什么,如果我使用 this
不带点 (.
).
this
引用当前对象.
每个非静态方法都在对象的上下文中运行.因此,如果您有这样的课程:
公共类 MyThisTest {私人int a;公共 MyThisTest() {这(42);//调用另一个构造函数}公共MyThisTest(int a){这.a = a;//将参数a的值赋给同名字段}公共无效frobnicate(){整数a = 1;System.out.println(a);//引用局部变量aSystem.out.println(this.a);//引用字段 aSystem.out.println(this);//引用整个对象}公共字符串 toString() {返回 "MyThisTest a=" + a;//引用字段 a}}
然后在
<上一页>142我的ThisTest a=42new MyThisTest()
上调用frobncate()
将打印
如此有效地将它用于多种用途:
- 澄清你是在谈论一个字段,当还有其他与字段同名的东西时
- 将当前对象作为一个整体引用
- 在你的构造函数中调用当前类的其他构造函数
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
这篇关于“这个"是什么意思?在 Java 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“这个"是什么意思?在 Java 中?
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01