Java - 何时使用“this”关键字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2429062/
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
Java - when to use 'this' keyword
提问by Hymanbot
What is the best practise for using the this
keyword in Java? For example, I have the following class:
this
在 Java 中使用关键字的最佳实践是什么?例如,我有以下课程:
class Foo {
Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
}
That's fine and all, but Java is clever enough to know what is happening if I change the statement in the constructor to
这很好,但 Java 足够聪明,知道如果我将构造函数中的语句更改为
bar = bar;
So why use the this
keyword? (I realise in some situations, it's totally necessary to use it, I'm just asking for situations like this). Actually, I tend to use the keyword purely for readability sake but what's the common practise? Using it all over the shop makes my code look a bit messy, for example
那么为什么要使用this
关键字呢?(我意识到在某些情况下,完全有必要使用它,我只是要求这样的情况)。实际上,我倾向于纯粹为了可读性而使用关键字,但通常的做法是什么?例如,在整个商店使用它会使我的代码看起来有点混乱
boolean baz;
int someIndex = 5;
this.baz = this.bar.getSomeNumber() == this.someBarArray[this.someIndex].getSomeNumber();
Obviously a poor bit of code but it illustrates my example. Is it just down to personal preference in these cases?
显然代码很差,但它说明了我的示例。在这些情况下,是否仅取决于个人喜好?
采纳答案by polygenelubricants
but Java is clever enough to know what is happening if I change the statement in the constructor to
bar = bar;
但是 Java 足够聪明,知道如果我将构造函数中的语句更改为
bar = bar;
FALSE! It compiles but it doesn't do what you think it does!
错误的!它编译但它没有做你认为它做的事情!
As to when to use it, a lot of it is personal preference. I like to use this
in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.
至于何时使用它,很多都是个人喜好。我喜欢this
在我的公共方法中使用,即使它是不必要的,因为那是接口发生的地方,并且很好地断言什么是我的,什么不是。
As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)
作为参考,您可以查看 Oracle 的 Java 教程关于 this.subject ;-)
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
回答by Andrew Hare
It is a personal preference - choose a style and stick to it. I personally use this
but others think it is redundant.
这是个人喜好——选择一种风格并坚持下去。我个人使用,this
但其他人认为它是多余的。
回答by Konrad Garus
Depending on convention, you can use it for readability. It stresses the fact that it's an object variable.
根据约定,您可以使用它来提高可读性。它强调了它是一个对象变量的事实。
I also like to have setter arguments with the same name as the variable (looks better in method signature). You need this
in this case.
我也喜欢使用与变量同名的 setter 参数(在方法签名中看起来更好)。this
在这种情况下你需要。
回答by Hyman
Actually
实际上
baz = baz
will raise this warning
将引发此警告
The assignment to variable baz has no effect
对变量 baz 的赋值无效
So what you think is wrong, the local scope overrides the class attribute so you MUSTuse this
keyword explictly to assign the variable to the class attribute.
所以你认为是错误的,局部作用域覆盖了 class 属性,所以你必须使用this
关键字显式地将变量分配给 class 属性。
Otherwise the variable accounted into assignment is just the one passed as a parameter and the class one is ignored. That's why this
is useful, it's not a fact of readability, it's a fact of explicitly deciding which baz
are you talking about.
否则,赋值的变量只是作为参数传递的变量,而忽略类 1。这就是为什么this
有用,这不是可读性的事实,而是明确决定baz
您在谈论哪个的事实。
I would say
我会说
use
this
wherever not using it would cause ambiguities (or compiler warning, that are more important), otherwise just leave it. Since its purpose is exactly to solve ambiguities when default assumptions (first check locals, then check class attributes) are not enough.
使用
this
的地方不使用会引起歧义(或编译器警告,这是更重要的),否则见好就收吧。因为它的目的正是在默认假设(首先检查局部变量,然后检查类属性)不够时解决歧义。
回答by Dónal Boyle
You should use it when you have a parameter with the same name as a field otherwise you will run into issues. It will compile, but won't necessarily do what you want it to.
当您有一个与字段同名的参数时,您应该使用它,否则您会遇到问题。它会编译,但不一定会按照您的意愿行事。
As for everywhere else, don't use it unless it's needed for readability's sake. If you use it everywhere, 20% of your code will consist of the word 'this'!
至于其他地方,除非为了可读性需要,否则不要使用它。如果在任何地方都使用它,那么 20% 的代码将包含“this”这个词!
回答by David Soroko
public Foo(Bar bar) {
this.bar = bar;
}
is not the same as
不一样
public Foo(Bar bar) {
bar = bar;
}
In the second case the bar in scope is the parameter, so you assign it to itself. this.bar
remains null
.
在第二种情况下,范围内的栏是参数,因此您将其分配给自身。this.bar
仍然null
。
回答by Decker
Personal preference, but I use it to solve ambiguities only, and I suppose in the very rare case to make it obvious that the assigned variable is a field. There are some projects where people use "this.field" on every single field reference. I find this practice visually distracting to the point of being obnoxious, but you should be prepared to see such code once in a while.
个人偏好,但我只用它来解决歧义,我想在极少数情况下,可以明确分配的变量是一个字段。在某些项目中,人们在每个字段引用上都使用“this.field”。我发现这种做法在视觉上会让人分心,甚至令人讨厌,但您应该准备好偶尔看到这样的代码。
I secretly think there's a special place in hell for people who write 500 line classes that have 275 'this' keywords in them, but this style is found in some open source projects, so to each his own I guess.
我暗自认为,对于那些编写 500 行包含 275 个“this”关键字的类的人来说,地狱有一个特殊的地方,但这种风格存在于一些开源项目中,所以我猜每个人都有自己的风格。
回答by Blessed Geek
I always try to use this
keyword on local class objects.
我总是尝试this
在本地类对象上使用关键字。
I use it to visually remind me if an object is static object or class object.
我用它来直观地提醒我一个对象是静态对象还是类对象。
It helps me and the compiler differentiate between method args and local class object.
它帮助我和编译器区分方法参数和本地类对象。
public void setValue(int value){
this.value = value;
}
It helps me to visually remind me if there is such a local object in an inner/nested/anonymous class to differentiate it from encapsulating class objects. Because if there is not this
prefixed, my convention will remind me that it is an object of the encapsulating class
它帮助我直观地提醒我内部/嵌套/匿名类中是否存在这样的本地对象,以将其与封装类对象区分开来。因为如果没有this
前缀,我的约定会提醒我它是封装类的对象
public class Hello{
public int value = 0;
public boolean modal = false;
public class Hellee{
public int value = 1;
public getValue(){
if (modal)
return 0;
return this.value;
}
}
}
回答by user291977
this
keyword refers to the Object of class on which some method is invoked.
For example:
this
关键字是指调用某些方法的类的对象。
例如:
public class Xyz {
public Xyz(Abc ob)
{
ob.show();
}
}
public class Abc {
int a = 10;
public Abc()
{
new Xyz(this);
}
public void show()
{
System.out.println("Value of a " + a);
}
public static void main(String s[])
{
new Abc();
}
}
Here in Abc()
we are calling Xyz()
which needs Object of Abc Class.. So we can pass this
instead of new Abc()
, because if we pass new Abc()
here it will call itself again and again.
在这里,Abc()
我们正在调用Xyz()
需要 Abc 类的对象..所以我们可以传递this
而不是 new Abc()
,因为如果我们Abc()
在这里传递 new它将一次又一次地调用自己。
Also we use this to differentiate variables of class and local variables of method. e.g
我们也用它来区分类的变量和方法的局部变量。例如
class Abc {
int a;
void setValue(int a)
{
this.a = a;
}
}
Here this.a
is refers to variable a of class Abc. Hence having same effect as you use new Abc().a;
.
这里this.a
是指类 Abc 的变量 a。因此与您使用 new 具有相同的效果Abc().a;
。
So you can say this
refers to object of current class.
所以你可以说this
是指当前类的对象。
回答by Buhake Sindi
Use it for Cloning objects (by passing reference of itself through a copy constructor).
将其用于克隆对象(通过复制构造函数传递自身的引用)。
Useful for object that inherits Cloneable
.
对继承Cloneable
.
public Foo implements Cloneable {
private String bar;
public Foo(Foo who) {
bar = who.bar;
}
public Object getClone() {
return new Foo(this); //Return new copy of self.
}
}