[英]What does this refer to in Java code?
我在Java初学者,我完全同意的定义混淆this
在Java中。 我已经读到它指的是current object
关注的current object
。
但是,这是什么意思 ? Who
的对象分配给this
? 我怎么会知道,而写我的代码what should be
值this
的时刻。
在简单地说,我完全迷茫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.