[英]this in java class (pointers)JAVA
public class Try {
String name="";
int age=13;
public void changer(Try t) {
t = this;
}
}
what does t=this
do in this code? t=this
在这段代码中有什么作用? I know this normally refers to the starting variable in top but int his case it looks like it does nothing?我知道这通常是指顶部的起始变量,但在他的情况下,它看起来什么都不做?
t= this
means you are assigning to local variable t
the current constructor object. t= this
意味着您将当前构造函数对象分配给局部变量t
。 this
refers to the current object. this
指的是当前对象。
this
always refers to the current object , you can refer here this
总是指当前对象,你可以参考这里
What does t=this do in this code? t=this 在这段代码中有什么作用?
It will assign the provided reference of t
to the current object.它将提供的t
引用分配给当前对象。
I know this normally refers to the starting variable in top but int his case it looks like it does nothing ?我知道这通常是指顶部的起始变量,但在他的情况下,它看起来什么都不做?
No, you are wrong, this does NOT refer to the starting variable in top, rather as mentioned above, it refers to the current object.不,你错了,这不是指顶部的起始变量,而是如上所述,它指的是当前对象。
The most common usage of this
is to initialize the variables of an object by using the constructor, as shown below: this
最常见的用法是通过构造函数来初始化一个对象的变量,如下所示:
public class Try {
String name; //initialize using constructor
int age; //initialize using constructor
//constructor
public Try(String name, int age) {
this.name = name; //assigns passed name value to current object's name
this.age = age; //assigns passed age value to current object's age
}
}
So It doesn't point to any address in data?所以它不指向数据中的任何地址?
this
holds the reference (think like a pointer in C
) of the current object. this
持有当前对象的引用(像C
的指针一样)。
If we assign two objects called t1 and t2 and say : t1=t2 it point to that address am I right?如果我们分配两个名为 t1 和 t2 的对象并说: t1=t2 它指向那个地址,对吗? but not in this case?但不是在这种情况下?
Yes, if you assign t1=t2
then you are making t1
to point to the same object as t2
ie, both t1
and t2
refer the same object on the heap.是的,如果您分配t1=t2
则您使t1
指向与t2
相同的对象,即t1
和t2
指向堆上的相同对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.