'this' is used to access the current object that is being used. What advantage does it have over passing the object itself since the method is going to access the current object that is being passes anyway.
It can help in many cases. The most obvious one is in constructors, when the parameter name is the same as an instance variable:
public final class Foo
{
private final int bar;
public Foo(final int bar)
{
this.bar = bar; // MUST specify "this" here
}
}
There can be a lot of usage of this
keyword. In java, this is a reference variable that refers to the current object. Usage of this
keyword
Here is given the 6 usage of this
keyword.
Read more about this Keywork
this
很少真正有必要 - 如果我没记错的话,只有当您有一个与局部变量同名的字段并且您想明确指定要访问该字段而不是局部变量时。
this
is used to access the current class variable
or methods
. Used to differentiate between instance variables ( ivars
) and local variables.
What advantage does it have over passing the object itself since the method is going to access the current object that is being passes anyway.
As per your question on advantage of using this
keyword over passing the object itself is this
is a final
variable in Java whereas the object when passed may or may not be final
. Being a final
variable, I can clearly see 2 main advantages of using this
over passing object itself.
One cannot assign any new value to the current instance of this
.
this = new Foo(); //compilation error; cannot assign value to final variable : this
It can be used in synchronized block.
synchronized(this){
/*this synchronized block will be locked on current instance*/
}
Apart from this context set up in the question, there are many advantages of using this
in Java which you can figure out from other answers.
Shishir
If I understand you correctly, you want to do
static void f(MyClass self) {
// access current class object using self
}
instead of
void f() {
// access current class object using this
}
and call the method this way
MyClass.f(instance);
istead of this
instance.f();
While this is actually possible you would always have to pass the current object as a parameter if it needs to be accessed. Why not just pass the object implicitly to non-static methods? This is what java does.
When you have a look at constructors, you will notice that there is no way to pass the current class object to it since the object does not exist before the constructor is called. So you could not access the current class object in constructors.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.