java “this.x”在java中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13104667/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:30:09  来源:igfitidea点击:

What does "this.x" mean in java?

javaclassinstance

提问by perldog93

Can someone please explain? As well as give a short and simple example. Thanks!

有人可以解释一下吗?以及给出一个简短而简单的例子。谢谢!

回答by Lews Therin

thisis a reference to the current object, and is implicitly passed into non static methods. this.xdereferences the reference to get to the "x" attribute.

this是对当前对象的引用,并隐式传递给非静态方法。 this.x取消引用以获取“x”属性。

Use it if you want to disambiguate between a function argument and a class member.

如果您想消除函数参数和类成员之间的歧义,请使用它。

public void setX(int x)
{
    this.x= x;
}

It is valid but redundant in this scenario:

在这种情况下它是有效但多余的:

public void setX(int xValue)
{
    this.x= xValue;
}

Or simply:

或者干脆:

public void setX(int xValue)
{
    x= xValue;
}