Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of ClassName.this beyond disambiguation?

Tags:

java

android

this

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?

like image 527
dcow Avatar asked Mar 29 '13 18:03

dcow


People also ask

What is classname this in Java?

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 .

Why do we use inner class?

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.


2 Answers

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();
  • See Java Tutorial: Nested Classes.
like image 185
Eng.Fouad Avatar answered Oct 07 '22 01:10

Eng.Fouad


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.

like image 29
CommonsWare Avatar answered Oct 07 '22 01:10

CommonsWare