这在Java代码中引用了什么?

时间:2012-10-10 12:03:32

标签: java this

我是JAVA的初学者,我对Java中this的定义感到困惑。我读过它指的是current object

但这意味着什么? Who将对象分配给this?我现在在编写what should be代码this的过程中如何知道。

简而言之,我对this感到困惑。任何人都可以帮我摆脱困惑吗?我知道this非常有用。

5 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

this是Java中的关键字,代表object本身。这包含在基础知识中。也许你可以浏览它上面的任何好文章。我从Oracle (formerly Sun Java tutorial)

给出一个

答案 2 :(得分:1)

this用于引用类中的变量。例如

public class MyClass {
    private Integer i;

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

在这段代码中,我们将参数i分配给类中的字段i。如果你没有这个,那么参数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来引用对象。它在您处理内部类并且想要引用外部类时使用。

答案 3 :(得分:1)

这很简单。

当前对象是代码在该点运行的对象。因此,它是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
  }
}

答案 4 :(得分:-1)

this指的是您当前的实例类。 this通常用于您的访问者。 E.g:

public void Sample{
 private String name;

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

请注意,this用于指定类Sample变量名称,而不是方法{中的参数 {1}}。

相关问题