2

不是重复的,这是一个语义问题?

哥伦比亚大学的一位教授说,关键字this,指向当前class见第 21 页)。我 99% 确定这是不正确的。

我想说它传递给 aclass instance或 an objectthis有没有一种首选的方式来简洁地说出什么意思。

谢谢,我只是希望我的笔记是准确的。

4

5 回答 5

7

来自Oracle 文档

关键字this只能用在实例方法、实例初始化器或构造器的主体中,或者在类的实例变量的初始化器中。如果它出现在其他任何地方,则会发生编译时错误。

...

当用作主要表达式时,关键字 this 表示一个值,该值是对调用实例方法的对象(第 15.12 节)或正在构造的对象的引用。

维基

这个

用于表示它出现的类的实例。this 可用于访问类成员并作为对当前实例的引用。this关键字还用于将调用从一个类中的一个构造函数转发到同一类中的另一个构造函数。

于 2013-09-29T12:49:22.223 回答
1

“这”指的是什么?

this 指的是current object

例如

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

不言自明的输出:

1
42
MyThisTest a=42
于 2013-09-29T12:50:59.270 回答
0

this肯定是指当前实例

于 2013-09-29T15:18:17.380 回答
0

this是 用于OO programming languages引用 的实例的关键字current class它隐式地获取当前类的对象或实例的引用或地址。

thisJAVA中

希望这可以帮助

于 2013-09-29T12:47:12.010 回答
0

您可以将其视为“当前类”。但我喜欢将其视为对使用“this”的对象实例的引用。

因此,如果您有类 A 并创建了两个实例 A1 和 A2,当您在 A2 中执行的方法调用中引用“this”时,“this”指的是实例 A2,而不是类 A。

清如泥?

于 2013-09-29T12:49:15.100 回答