I see some code use class_name.this
as a parameter for its context, and sometimes use this
directly in another demo code. May I assume that this
is a abbreviation of class_name.this
?

- 631
- 1
- 7
- 16
-
possible duplicate of [What is the difference between Class.this and this in Java](http://stackoverflow.com/questions/5666134/what-is-the-difference-between-class-this-and-this-in-java) and [Java: Class.this](http://stackoverflow.com/questions/5530256/java-class-this). – Matt Ball Sep 17 '13 at 05:21
5 Answers
We use this
when if the class references can be type-casted to Context. And when this
object cann't be, then we use ClassName.this
(BUT only if the class is child/ super child [subclass] of Context class. like Activity/ Services)
Read What is 'Context' on Android?
Let me explain by example code (For example I am using Activity
and AsyncTask
)
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.startActivity(intent);
// or
MainActivity.this.startActivity(intent);
// Both are same here.
}
private class TestTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(Void result) {
this.startActivity(intent); // You can not do. Because "this" is the current object of AsyncTask not of Activity.
// So you can only use
MainActivity.this.startActivity(intent);
}
}
}

- 1
- 1

- 81,967
- 29
- 167
- 186
1.In Outer Class you directly use "this" reference
2.In Inner Class Or Abstract Class implementation Or Interface implementation use "classname.this" reference

- 24,720
- 5
- 57
- 67
This is special syntax which allows to access outer class instance from an inner class. Consider this
class X {
class Y {
void y() {
Object y = this;
Object x = X.this;
}
}
}

- 133,369
- 30
- 199
- 275
ClassName.this
allows you to refer to the external class even when inside a nested class.
For example MyClickListener
is nested inside MainAcvitiy
:
private class MyClickListener implements OnClickListener
{
@Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "I have been clicked", Toast.LENGTH_SHORT).show();
}
}
You need the reference to MainActivity.this
because the current value of this
is MyClickListener
and you don't want to bother passing in a reference to the Activity here

- 1,840
- 1
- 15
- 22
this is used to refer the current or live instance of class , but in cases where u have to use nested classes and nested class wants to access the member of outer class then its done by using class_name.this as it will make clear which class u are referring to.
refer this questions :-
What is the difference between Class.this and this in Java