繁体   English   中英

这在Java代码中指的是什么?

[英]What does this refer to in Java code?

我在Java初学者,我完全同意的定义混淆this在Java中。 我已经读到它指的是current object关注的current object

但是,这是什么意思 ? Who的对象分配给this 我怎么会知道,而写我的代码what should bethis的时刻。

在简单地说,我完全迷茫this 谁能帮助我摆脱混乱? 我知道this非常有用。

this是Java中的关键字,代表object本身。 这是基础知识。 也许您可以浏览所有关于它的好文章。 我正在从Oracle提供一个(以前是Sun Java教程)

this用于刷新类中的变量。 例如

public class MyClass {
    private Integer i;

    public MyClass(Integer i) {
      this.i = i;
    }
}

在此代码中,我们将参数i分配给类中的字段i。 如果您没有this,那么参数i将被分配给它自己。 通常,您使用不同的参数名称,因此不需要此名称。 例如

public class MyClass {
    private Integer i;

    public MyClass(Integer j) {
      this.i = j;
      //i = j; //this line does the same thing as the line above.
    }
}

在上面的例子中,你不需要this的盈方i

总之,您可以使用它在所有类字段之前。 大多数情况下,您不需要这样做,但是如果存在任何类型的名称隐藏,则可以使用this来明确表示您正在引用字段。

您也可以使用this来引用对象。 当您处理内部类并想引用外部类时,可以使用它。

这很简单。

当前对象是其代码正在该点运行的对象。 因此,它是this代码出现在的类的实例。

实际上,除非您在对象和本地范围内具有相同的标识符,否则通常可以删除this标识符,并且其工作原理也完全相同。

无法删除此示例

public class myClass {
  private int myVariable;
  public setMyVariable(int myVariable) {
    this.myVariable = myVariable; // if you do not add this, the compiler won't know you are refering to the instance variable
  }
  public int getMyVariable() {
    return this.myVariable;  // here there is no possibility for confussion, you can delete this if you want
  }
}

this是指您当前的实例类。 this通常用于您的访问器。 例如:

public void Sample{
 private String name;

 public setName(String name){
  this.name = name;
 }
}

请注意, this用于专门指向类Sample变量名,而不是方法setName中的参数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM