java - Java中 "this"是什么意思?

标签 java this

通常,我仅在构造函数中使用 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/

相关文章:

java - 检查整个文本是否与正则表达式的一部分匹配?

java - 一种从 Artifact 中删除 jar 的方法

jquery - $(this) 在 jQuery 顶层的含义

javascript - this.function 不是函数错误,而是函数存在

java - 如何在Android上写好 "time limited features"?

修改主机操作系统默认值后,Java 检测时区

javascript - 如何复用函数属性?

c++ - 可能的段错误 : Am I using the "this->" operator correctly?

javascript - jquery 使用 $(this) 不起作用

Java读取pptx文件