【问题标题】:Greenfoot, using "this" [duplicate]Greenfoot,使用“这个”[重复]
【发布时间】:2014-03-09 20:54:30
【问题描述】:

我刚开始使用greenfoot,正在研究一些例子,发现人们经常使用“this”,它到底是什么意思,我不太明白,例如:

//set the animal's age
public void setAge(int age)
{
   this.age = age;
}

【问题讨论】:

  • 来吧,只要在 Google 或 SO 中搜索“this”即可。
  • 我做了,但我想我会在这里得到更好的解释。

标签: java greenfoot


【解决方案1】:

this 指的是对象的当前实例。所以,在你的例子中:

public void setAge(int age)
{
   this.age = age;
}

在setAge 设置器中使用this 意味着我们在this.age 中引用实例变量age 并将其设置为等于参数age 的值。这意味着this.age 和age 指的是不同的变量。

【讨论】:

    【解决方案2】:

    关键字

    this
    

    指的是封闭类的一个实例。在您的示例中,“this”将引用包含该关键字的类。

    您的问题可能已经在这里得到解答:

    What is the meaning of "this" in Java?

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 2011-03-21
      • 1970-01-01
      • 2020-10-18
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      相关资源
      最近更新 更多