Java中的“this”是做什么的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21817600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does "this" do in Java?
提问by Waqas Ahmed
k, I am going through few Game Development Tutorials of Java, and I have to work with Threads and there is a "this" thing Thread thread = new Thread(this); that I am unable to understand, I am implementing my Class by "Runnable". What I think about it, is that "this" refers to Runnable to seek for the Run Method that I have defined in MY Class. And If I don't do this, It won't be looking for Run() Method here in my Class. Don't really know If M-Effed, but please correct me If I am wrong....
k,我正在学习一些 Java 游戏开发教程,我必须使用 Threads 并且有一个“这个”东西 Thread thread = new Thread(this); 我无法理解,我正在通过“Runnable”实现我的类。我的想法是,“this”指的是 Runnable 以寻找我在 MY Class 中定义的 Run 方法。如果我不这样做,它就不会在我的类中寻找 Run() 方法。真的不知道是否 M-Effed,但如果我错了,请纠正我....
采纳答案by óscar López
this
is a pseudo-variablethat points to the current instance, to the object itself where the method is being executed. So for example:
this
是一个伪变量,指向当前实例,指向正在执行方法的对象本身。例如:
public class Person {
private String name;
public void setName(pName) {
this.name = pName
}
}
Person p = new Person();
p.setName("Peter");
In the above code, we're assigning the new name
"Peter"
to thisperson p
, the current instance of the class Person
. In other words, from the point of view of p
, this
is pointing to p
.
在上面的代码中,我们将 new 分配name
"Peter"
给这个person p
,即类的当前实例Person
。换句话说,从 的角度来看p
,this
是指向p
。
回答by Stephen C
@óscar López explains what this
means.
@óscar López 解释了这this
意味着什么。
If your code contains this:
如果您的代码包含以下内容:
Thread thread = new Thread(this);
then this
refers to an instance of the class that contains that statement. Furthermore, it is theinstance that is running the code. Furthermore, the API spec of that Thread
constructors means that this
needs to be an instance of a class that implements Runnable
.
thenthis
引用包含该语句的类的实例。此外,它是运行代码的实例。此外,该Thread
构造函数的 API 规范意味着它this
需要是实现Runnable
.
In short, your class needs to be declared as implements Runnable
, and it needs to have a method with this signature:
简而言之,您的类需要声明为implements Runnable
,并且它需要有一个具有此签名的方法:
public void run()