Java中的“this”是什么意思?

新手上路,请多包涵

通常,我只在构造函数中使用 this

我知道它用于识别参数变量(通过使用 this.something ),如果它与全局变量具有相同的名称。

但是,我不知道 this 在 Java 中的真正含义是什么,如果我使用 this 没有点( . )会发生什么。

原文由 guilgamos 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 471
1 个回答

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
  }
}

然后在 --- frobnicate() new MyThisTest() 将打印

1个
42
MyThisTest a=42

如此有效,您可以将它用于多种用途:

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

原文由 Joachim Sauer 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题