[ACCEPTED]-Using "this" with class name-this

Accepted answer
Score: 142

Usually, you can use only this. But, sometimes 2 this makes reference to an inner class... so, for 1 example:

Button button = (Button)findViewById(R.id.ticket_details_sell_ticket);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // it will be wrong to use only "this", because it would
        // reference the just created OnClickListener object
        Intent login = new Intent(ClassName.this, Login.class);
        startActivityForResult(login, LOGIN_REQUEST);
Score: 65

One at a time:

The first construct is called 14 a qualified this. The purpose of the syntax is in the 13 case where you are in an inner class (typically 12 an anonymous inner class) and you want to 11 reference the this of the outer class rather 10 than the this of the (anonymous) inner class. The 9 "qualified this" can only be used 8 in a context where this would be ambiguous. The 7 quote the JLS "It is a compile-time 6 error if the expression occurs in a class 5 or interface which is not an inner class 4 of class T or T itself".

The second 3 construct is called a class literal is the way to reference 2 the Class object that represents that type. It 1 can be used in any context.

Score: 14

The syntax "Classname.this" is for inner 5 classes. If you want to refer to the enclosing 4 instance of type "Outerclass" then you do 3 it as "Outerclass.this".

NextActivity.class 2 is simply the Class object that describes 1 class "NextActivity".

Score: 12

NextActivity.class in java means typeof(NextActivity) in C#


Score: 8

ClassName.this is used to reference the current instance 1 of an outerclass from an inner class.

Score: 5

is used in nested classes to refer to the 3 current instance of the enclosing class, since 2 the `this' keyword refers to the nest class 1 instance.

public class Siht {
    class NestedSiht {
        void demoThis() {
            System.err.println("this' is an instance of: " + 
            System.err.println("Siht.this' is an instance of: " +

void demoThis() {
    new java.lang.Object() {
        void demoThis() {
            System.err.println("`this' is an instance of: " + 
            System.err.println("`Siht.this' is an instance of: " +
    new NestedSiht().demoThis();

public static void main(String [] args) {
    new Siht().demoThis();


Score: 0

It's confusing only because when you use 11 "MainActivity.this", it seems that you are referring 10 to the class and not the object. In reality 9 when you use "this" you are always 8 referring to the current object, as the 7 java se documentation states:


Within an instance 6 method or a constructor, this is a reference 5 to the current object — the object whose method or constructor 4 is being called. You can refer to any member 3 of the current object from within an instance 2 method or a constructor by using this.

It's 1 just syntactically peculiar.

More Related questions