I've seen ClassName.this
used in a lot of Android code on SO and other places online (rather than the simple this
keyword) to refer to the current instance of a class. I understand you may decide to preface this
with the class name in order to remove any ambiguity, but in my experience doing so is often unnecessary as there can really only be one thing this
refers to -- the current instance of the class the code is executing in. Is there something else I'm overlooking that would suggest prefacing the this
keyword with a class name is always the better practice, or are there any situations where it is, in fact, necessary?
The Classname. this syntax is used to refer to an outer class instance when you are using nested classes; see Using "this" with class name for more details. However this. Classname is a compilation error ... unless you have declared an instance (or static) field with the name Classname .
We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable. Additionally, it can access all the members of the outer class, including private data members and methods.
To access the instance of the enclosing-class from inside the inner classes or the anonymous classes, you need to use this syntax:
EnclosingClass.this.someMethod();
there can really only be one thing this refers to.
That is incorrect.
Is there something else I'm overlooking that would suggest prefacing the this keyword with the class name is always the better practice or are there any situations where it is necessary?
Yes and yes, respectively. In particular, ClassName.this
is needed from inner classes to get to the outer class instance of this
.
For example:
myButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MyActivity.this, MyOtherActivity.class));
}
});
Here, using this
instead of MyActivity.this
will fail with a compile error, complaining that Button.OnClickListener
is not a valid first parameter to the Intent
constructor. MyActivity.this
returns the this
that is the MyActivity
instance that encloses the Button.OnClickListener
instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With