0

我是 JAVA 的初学者,我完全对thisJava 中的定义感到困惑。我读过它指的是current object有关方面。

但是,这是什么意思 ?Who将对象分配给 this? 以及我在编写代码时如何知道此刻what should be的价值this

简而言之,我对this. 谁能帮我摆脱我的困惑?我知道这this非常有用。

4

5 回答 5

2

按照这两个链接: -

http://javapapers.com/core-java/explain-the-java-this-keyword

http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

于 2012-10-10T12:06:28.543 回答
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
  }
}
于 2012-10-10T12:09:13.333 回答
1

this是 Java 中的一个关键字,代表object自身。这包含在基础知识中。也许你可以浏览任何关于它的好文章。我从Oracle(以前的 Sun Java 教程)中提供一份

于 2012-10-10T12:07:56.090 回答
1

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来引用一个对象。当您处理内部类并想要引用外部类时使用它。

于 2012-10-10T12:08:04.280 回答
-1

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

public void Sample{
 private String name;

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

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

于 2012-10-10T12:06:37.713 回答