“这个"是什么意思?在 Java 中?

2022-01-30 00:00:00 this 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}}

然后在 new MyThisTest() 上调用 frobncate() 将打印

<上一页>142我的ThisTest a=42

如此有效地将它用于多种用途:

  • 澄清你是在谈论一个字段,当还有其他与字段同名的东西时
  • 将当前对象作为一个整体引用
  • 在你的构造函数中调用当前类的其他构造函数

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

相关文章