Using "this" with class name Using "this" with class name java java

Using "this" with class name


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

Button button = (Button)findViewById(R.id.ticket_details_sell_ticket);button.setOnClickListener(new OnClickListener() {    @Override    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);    }});


One at a time:

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

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


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

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