How is "this" used when it comes to a class?

I don't quite understand how the keyword is used in this case this

.

private void checkForComodification() {
    // The this I'm concerned about is the first one
    if (CyclicArrayList.this.modCount != this.modCount)
        throw new ConcurrentModificationException();
}

      

+3


source to share


2 answers


This is sometimes needed in inner classes.

this

points to an internal instance of the class.



MyOuterClass.this

points to the contained instance of the class.

In your case, this is necessary because both classes have a property modCount

(and one of the outer class is CyclicArrayList

shaded here).

+5


source


It is used for inner classes where you need an attribute or method in the "outer" scope that has the same name as in your current class.

By default, the 'this' keyword refers to the current class scope, without this function you will not have access to external fields and methods with the same name.



public class Outer {
  private String test = "outer;
  private class Inner {
    private String test = "inner";
    public void foo() {
       System.out.println(this.test);       // "inner"
       System.out.println(Outer.this.test); // "outer"
    }
  }
}

      

+3


source







All Articles